3

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.

3
  • You may also need to configure Data Protection (learn.microsoft.com/en-us/aspnet/core/security/data-protection/…), as otherwise the session might be being protected by in-memory keys that are lost when the application restarts. This doesn't happen locally in Visual Studio as the keys are stored in your user profile. Commented Apr 3, 2017 at 10:48
  • Wouldn't that end up in the same result, as the sessions itself are head into memory too when the server restarts unless he uses something like redis? Commented Apr 3, 2017 at 10:59
  • 1
    I was rendering in an iframe so I had to add options.Cookie.SameSite = SameSiteMode.None; to services.AddSession Commented May 17, 2018 at 19:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.