I am developing ASP.Net MVC 5.0 application, . Now I have created login page. when user is valid I am storing user details into seesion.
if(_loginmodel.authstatus == false)
{
return View("Index");
}
Session["authstatus"] = true;
Session["userid"] = _loginmodel.userid;
Session["useremail"] = _loginmodel.useremail;
Session["username"] = _loginmodel.username;
No when user go to other files I am again checking session available or not
public class CityController : Controller
{
private CityModels _citymodel;
#region Constructor
public CityController()
{
if (Session != null && Session["authstatus"] != null)
{
_citymodel = new CityModels();
}
RedirectToAction("Index", "Login");
}
#endregion
}
so now how can i redirect him to login page if session expired
I think you could wrap this logic inside an action filter, and redirect in there:
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (session != null && session ["authstatus"] == null)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "Login" },
{ "action", "Index" }
});
}
}
base.OnActionExecuting(filterContext);
}
}
more details in here:
https://stackoverflow.com/a/5453371/1384539
Write code in web.config file to set the session timeout to 2 minutes
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="1" />
</authentication>
<sessionState timeout="2"></sessionState>
<globalization uiCulture="en" culture="en-GB"/>
</system.web>
Write the code below in a <script>
tag in layout.cshtml
//session end
var sessionTimeoutWarning = @Session.Timeout - 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location.hostname = "";
/* $(window.Location).attr("href", "@Url.Content("~/Login/index/")"); */
window.location = "/Login/index/";
}
Write the code below in control and action
[HttpGet]
public ActionResult Logout()
{
Session["id1"] = null;
Session["id2"] = null;
Session["id3"] = null;
Session["id4"] = null;
Session["Region"] = null;
Session.Clear();
Session.RemoveAll();
Session.Abandon();
Response.AddHeader("Cache-control", "no-store, must-revalidate, private, no-cache");
Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Expires", "0");
Response.AppendToLog("window.location.reload();");
return RedirectToAction("Index", "Login");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With