I have looked all over, but have found no answer that works for me. Whenever I am working in the localhost, my user never gets logged out and the session is remembered so I don't have to log in again. However, when I publish it (I use HostGator's ASP.NET hosting) the user gets randomly logged out after a few minutes or after an HTTP request. Some answers I have seen include HostGator needing to have an ASP.NET Core hosting module, my web.config using a machine key, and using services.AddSession
, but I haven't had any luck.
Here's my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AuthDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequiredLength = 10;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
})
.AddEntityFrameworkStores<AuthDbContext>()
.AddDefaultTokenProviders();
services.AddMvcCore();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddMvcCore().AddRazorRuntimeCompilation();
services.AddMemoryCache();
services.AddSession(options =>
{
options.Cookie.IsEssential = true;
options.IdleTimeout = TimeSpan.FromHours(6);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// Authentication must always go before Authorization
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
Here's my Login method in the Account controller:
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel lvm)
{
if (ModelState.IsValid)
{
var result = await signInManager.PasswordSignInAsync(lvm.Email, lvm.Password, lvm.RememberMe, false);
if (result.Succeeded)
{
return Redirect(lvm.ReturnURL);
}
ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}
return View(lvm);
}