You must Sign In to post a response.
  • Category: ASP.Net MVC

    Check session value after login in MVC

    Hello.
    I am new to MVC.
    I have worked on web application.
    My requirement is, if I have 2 pages, login and home.
    If user directly enters URL of Home in browsers, it should first check for session values related to user.
    For this, I have created 1 class names as "base", where I checked session contains value or not.
    Home page inherited from base class, so that it automatically redirect to login page.
    Same scenario I want in MVC5.
    I have 2 controllers, Login and Student.
    After login, I store session values into base class.
    I want to create above scenario so that, if user enters url in browser, it first check for session.
    Its like controller inherit from controller / class.
  • #768094
    Hi Pranjal,

    Basically the method you are followed for last application was also not the correct way.
    Now you got one function so you are checking the session and redirecting to login page. In future if you got 50 function each function you can redirect from there. So in MVC we have simple and effective method to implement this in Global.asax


    public class SessionAuthorizeAttribute : AuthorizeAttribute
    {
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
    if(session have value)
    {
    // proceed
    }
    else
    {
    // redirect to login
    }
    }

    }


    Now in controller you can call this validating function all place like,


    [SessionAuthorize]
    public class AnyController
    {
    }



    So in a single implementation of code in Global.asax, you can use it any where in controller.

    Thanks,
    Mani

  • #768095
    Hai Pranjal,
    You can decorate your controllers with the class which can have the session authorization logic. MVC supports decorate of the class for the authorization so you can make use of it for the session validation.

    [SessionAuthorization]
    public class HomeController : Controller
    {
    // logic for controller
    }

    [SessionAuthorization]
    public class LoginController : Controller
    {
    // logic for controller
    }

    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com


  • Sign In to post your comments