Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 995
charan Avatar asked Sep 03 '15 18:09

charan


2 Answers

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

like image 80
Thiago Custodio Avatar answered Nov 18 '22 08:11

Thiago Custodio


  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");
    }
    
like image 27
user6284267 Avatar answered Nov 18 '22 08:11

user6284267