简体   繁体   中英

How to redirect to login page if session is not available in MVC

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

  1. 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>
  2. 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/"; }
  3. 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"); }

You should create a custom filter attribute to handle session expiry, as follows -

public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Custom attribute for handling session timeout
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        // check if session is supported
        if (ctx.Session != null)
        {
            // check if a new session id was generated
            if (ctx.Session.IsNewSession)
            {
                // If it says it is a new session, but an existing cookie exists, then it must
                // have timed out
                string sessionCookie = ctx.Request.Headers["Cookie"];
                if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                {
                    ctx.Response.Redirect("~/Error/SessionTimeoutVeiw");
                }
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

Now to use this custom attribute, decorate your controller method or class with this attribute.

[SessionExpireFilterAttribute]

And if you need to apply this filter to be applicable for all controllers, you can register this filter in FilterConfig file.

So when a session expires, so as the values in the session, you need not to check if a perticular session value has expired.

You can redirect user to login page on Session_Start event in Global

protected void Session_Start()
        {            
            if (Session["Username"] != null)
            {
                //Redirect to Welcome Page if Session is not null  
                HttpContext.Current.Response.Redirect("~/WelcomeScreen", false);

            }
            else
            {
                //Redirect to Login Page if Session is null & Expires                   
                new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Login" } });
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM