How can I maintain the session of the user in ASP.NET MVC? Here is the login case for the user. (Only authenticated users are allowed to login in the system.) But once the user gets logged in and press the back button then the user needs to login again. I want to solve this issue. Can anyone have idea about it?
using HolidayPlanner20.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HolidayPlanner20.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(tbl_users userModel)
{
if (ModelState.IsValid)
{
using (DbModels db = new DbModels())
{
var obj = db.tbl_users.Where(a => a.Username.Equals(userModel.Username) && a.Password.Equals(userModel.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserID.ToString();
Session["Username"] = obj.Username.ToString();
return RedirectToAction("UserDashBoard");
}
}
}
return View(userModel);
}
public ActionResult UserDashBoard()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
}
}
Not an issue here, when you press back, it doesn't always request to the server again. The user is seeing a cached page. Either don't worry about it or set no-cache headers on the page to prevent the browser from caching it.
OR you can simply disable browser back button after login using the script below
<script language="JavaScript" type="text/javascript">
//remove back button with all possibilities
function noBack() { window.history.forward() }
noBack();
window.onload = noBack;
window.onpageshow = function(evt) { if (evt.persisted) noBack() }
window.onunload = function() { void (0) }
//remove forward buttons
javascript:window.history.forward(1);
</script>
above code was in the question of this link, https://qawithexperts.com/questions/36/disable-browser-back-forward-button-after-logout-in-mvc
OR disable browser cache using meta tags
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly