【发布时间】:2020-11-16 21:18:05
【问题描述】:
我目前正在开发一个项目,该项目由一个简单的前端(作为一个 HTML 页面)和一个 ASP.NET Core 后端 (Web-API) 组成。我目前正在处理注册/登录过程。登录方法由 GET 请求触发,注册方法由 POST 请求触发。 register 方法为会话 cookie 设置了四个值,我们称它们为 valA、valB、valC 和 valD。之后,使用 login 方法获取对应的值。到目前为止,我已经尝试了以下解决方案来使其正常工作:
- 修改 CookiePolicyOptions 以绕过 ConsentCheck 并将 SameSitePolicy 设置为“None”
- 应用了上述 CookiePolicy
- 检查用户控制器是否有错误 - 到目前为止没有任何错误
更新
有几个因素导致了前面提到的情况。首先,就像建议的标记答案一样,cookie 被发送到客户端,但没有返回。这个问题有几个原因。第一个问题是我的 HTML javascript 代码正在发送登录请求。这可以通过在客户端添加以下代码并将以下函数设置为登录按钮的 OnClickHandler 来解决:
function PostLoginRequest()
{
fetch(someUrl,{
/*
* The credentials header enables the sending
* process of the response cookie, while the
* sameSite header is used to enable the cookie
* sent accross the original domain (in this case, the HTML file)
*/
"credentials":"include",
"sameSite":"None"
});
}
此外,您还必须调整 Startup.cs 文件的 ConfigureServices 方法的内容。在这种情况下,您将添加以下新行:
// Configure a cookie policy which will be enforced by the Web API
services.Configure<CookiePolicyOptions>(options=>{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
options.Secure = CookieSecurePolicy.Always;
});
// Add a storage for the session cookies, in this case a DMC
services.AddDistributedMemoryCache();
// Configure the session cookie
services.AddSession(options=>{
// Set the name of the session cookie
options.Cookie.Name = ".App.Session";
// How long should the cookie be stored? (in this case 1 day from now)
options.IdleTimeOut = TimeSpan.FromDays(1);
// Can we bypass the consent check? (in this case : yes)
options.Cookie.IsEssential = true;
// Prevent the cookie to be accesible via Javascript
options.Cookie.HttpOnly = true;
// Allow the cookie to be sent to other domains
options.Cookie.SameSite = SameSiteMode.None;
// Sets the path of the cookie. This means on which segment of
// the domain it will be accessible. In this case, the whole domain
// is covered by the cookie
options.Cookie.Path = "/";
});
最后,Startup.cs 应该包含函数调用 app.UseSession() 和 app.UseCookiePolicy() .虽然第一个调用使 ASP.NET Core 服务器能够发送会话 cookie,但如果其中存储了一些值,第二个调用将应用我们之前定义的 cookie 策略。到目前为止,这应该是一切。很抱歉更新了这么久,但我希望我的解决方案描述可以帮助其他面临同样问题的人。
【问题讨论】:
-
正在使用什么数据库?看起来来自数据库的查询返回 null。您是否使用嗅探器确定响应为空?
-
到目前为止没有使用数据库。据我了解,会话数据存储在由服务器本身组织的 In-Memory-Cache 中。因此,到目前为止我没有使用任何数据库。就一般数据库使用而言,我使用本地 MariaDB 实例来存储会话数据以外的所有内容。
-
数据存储在类中。因此,如果您丢失的数据多于一个类实例(或使用 NEW 调用构造函数并清除旧数据)。
-
这里可能有误会。我的会话数据未存储在包含所有会话数据的任何类中。我只是在相应的控制器中设置值并检索它们。我没有任何构造函数,只有带有 Session 对象的 HttpContext 和他的相关方法,如 GetString(x) 或 GetInt32(y)。但是,Rajdeep 的评论在这种情况下可能会有所帮助。但是,我必须感谢您的建议 :)
-
数据必须存储在某个地方。
标签: c# asp.net session controller