会话在Asp.net核心应用程序中丢失

时间:2017-04-03 10:41:48

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

我在我的应用程序中使用AddDistributedMemoryCache进行会话,

继续在IIS中丢失会话。程序Session在Visual Studio中运行良好

调试模式。

这是启动代码:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddOptions();
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    services.AddMvc();
    services.AddDistributedMemoryCache();
    services.AddSession(opts =>
    {
        opts.IdleTimeout = TimeSpan.FromMinutes(45);
    });
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseSession();


    app.UseHttpMethodOverride();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}"
            );
        routes.MapRoute(
            name: "AdvertisementImages",
            template: "{controller=MainImage}/{action=Images}/{type}/{name}", // URL with parameters
            defaults: new {type = 0, name = ""} // Parameter defaults
        );
    });
}

这就是我如何填充会话和反复值:

var newLogin = HttpContext.Session.GetObjectFromJson<TryToLoginModel>("TryToLogin");

和GetObjectFromJson的扩展:

public static class SessionExtensions
{
    public static void SetObjectAsJson(this ISession session, string key, object value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T GetObjectFromJson<T>(this ISession session, string key)
    {
        var value = session.GetString(key);

        return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
    }
}

在几次调用 HttpContext.Session.GetObjectFromJson 后,它返回null。问题只发生在IIS而不是visual studio。

0 个答案:

没有答案