问题
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