【问题标题】:Session value not preserved or not working in dotnetcore webapi会话值未保留或在 dotnetcore webapi 中不起作用
【发布时间】:2019-04-17 18:34:08
【问题描述】:

下面是我的startup.cs代码,

public void ConfigureServices(IServiceCollection services){  
    services.AddMvc().AddJsonOptions(options =>{
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

    services.AddDistributedMemoryCache();

    services.AddSession(options => {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(36000);
        options.Cookie.HttpOnly = true;
    });

    services.AddCors(options => {
        options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
    });
}

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

    app.UseStaticFiles();

    //app.UseCors("CorsPolicy");
    // global cors policy
    app.UseCors(x => x
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());

    app.UseSession();
    app.UseAuthentication();
    app.UseMvc();
}

下面是在 session 中设置和获取 userid 的代码:

HttpContext.Session.SetInt32("UserId", user.Id);
int userId = (int)HttpContext.Session.GetInt32("UserId");

我在以不同于设置的操作的操作中读取会话时遇到异常。会话不工作的任何原因?

【问题讨论】:

  • 你得到了什么异常?
  • 如果我猜对了。您在method A 中设置HttpContext.Session.SetInt32("UserId", user.Id);,然后method A 正在调用您尝试使用HttpContext.Session.SetInt32("UserId", user.Id);method B
  • 可空对象必须有值。
  • 没有塞巴斯蒂安。如果它是相同的动作,那么我不需要会话本身。我们需要用于维护不同 HTTP 请求之间的状态的会话。我在不同的控制器操作中设置会话并在不同的控制器操作中获取它。

标签: c# session asp.net-web-api .net-core


【解决方案1】:

此解决方案仅适用于 dotnetcore 2.1 或更高版本。我的解决方案是 dotnetcore 2.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多