ASP 网络核心 2.1 Session

ASP Net Core 2.1 Session

我目前正在 .Net Core 2.1 中开发 API 使用带有 Nuxt 的 Vue 2 中的客户端应用程序,我在 ASP .Net 中的 session 中保存 object 时遇到问题。 在问这个问题之前,我已经查看了 this 和其他链接,但没有任何帮助。 事实证明我已经用 Postman 试过了,如果它有效,但我不明白为什么它不适用于我的应用程序。

这是我的Startup.cs

public class Startup
    {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => false;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
// Add Database
// End Add Database
    services.AddCors(options => 
{
    options.AddPolicy("AllowSpecificOrigin", builder =>
    builder.AllowAnyHeader()
           .AllowAnyMethod()
           .AllowAnyOrigin()
));
});
 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    .AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(1440);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCookiePolicy();
    app.UseCors("AllowSpecificOrigin");
    app.UseSession();
    app.UseMvc();
}
}

在我的控制器中:

[Route("api/customer/[controller]")]
[ApiController]
public class ClientController : ControllerBase { ...

... 获取并设置 Session Var

var model = HttpContext.Session.GetString("User")

和其他控制器

HttpContext.Session.SetString("User", "Hello World")

每次我为 ajax 发出请求时,HttpContext 都会更改 ID,但邮递员不会更改 ID,这就是我可以恢复 cookie 的原因。

您可能需要在发出 AJAX 请求时设置 withCredentials 标志。同站点请求不需要这样做,但是您提到了 CORS 并且没有指定它是同站点。对于 jQuery,这只是意味着将它添加到 AJAX 选项对象中的 xhrFields

$.ajax({
    ...
    xhrFields: {
        withCredentials: true
    }
});

其他库可能有不同的方法,但都应该有某种方法在 XMLHttpRequest 对象上设置此标志。