Session Lost in Asp.net Core application

…衆ロ難τιáo~ 提交于 2021-02-07 09:15:31

问题


Im Using AddDistributedMemoryCache for session in my application and

keep losing my session in IIS. the program Session works well in Visual Studio

Debug mode.

this is Startup Code :

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
        );
    });
}

and this how i fill session and retrive value :

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

and Extension for 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);
    }
}

after few call to HttpContext.Session.GetObjectFromJson It returns null. problem happens in IIS only and not visual studio.

来源:https://stackoverflow.com/questions/43182480/session-lost-in-asp-net-core-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!