繁体   English   中英

ASP Net Core Web API 无法识别 session 数据

[英]ASP Net Core Web API doesn't recognize session data

我目前正在开发一个项目,该项目由一个简单的前端(作为一个 HTML 页面)和一个 ASP.NET 核心后端(Web-API)组成。 我目前正在处理注册/登录过程。 登录方法由 GET 请求触发,注册方法由 POST 请求触发。 注册方法是为 session cookie 设置四个值,我们称它们为 valA、valB、valC 和 valD。 之后,使用 login 方法获取对应的值。 到目前为止,我已经尝试了以下解决方案来使其正常工作:

  • 修改 CookiePolicyOptions 以绕过 ConsentCheck 并将 SameSitePolicy 设置为“None”
  • 应用说 CookiePolicy
  • 检查用户 controller 是否有错误 - 到目前为止没有任何错误

更新

有几个因素导致了前面提到的情况。 首先,就像建议的标记答案一样,cookie 被发送到客户端,但没有返回。 这个问题有几个原因。 第一个问题是我的 HTML 的 javascript 代码正在发送登录请求。 这可以通过在客户端添加以下代码并将以下 function 设置为登录按钮的 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应该包含 function 调用app.UseSession()app.UseCookiePolicy() 虽然第一个调用使 ASP.NET 核心服务器能够发送 session cookie,但如果其中存储了一些值,则第二个调用应用我们之前定义的 cookie 策略。 到目前为止,这应该是一切。 很抱歉更新了很长时间,但我希望我的解决方案描述可以帮助其他面临同样问题的人。

您的 HTML 页面需要重新发送 cookies,如果它没有发送 ASP.Net web Z8A5DA52ED0264427D35AZE 无法接收任何值。 在这里,您的 Asp.Net web api 只是一个 api,它无法控制您的 ZFC35FDC70D5FC69D23EZ 页面。 您如何从 HTML 页面拨打 api 电话?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM