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

.netasp.netasp.net-mvcc++

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

Best Solution

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

Related Question