简体   繁体   中英

globally session check and redirection in asp.net mvc 4

I am developing a web application using ASP.Net MVC 4, the application has one login page and 5 other pages which will be accessible by logged in users only. So how do i globally check the existence of session in all the pages without writing the following code in all the other pages(Actions) : -

if (Session["login"] != null)
        {
            return View();
        }
        else
        {
            return RedirectToAction("LoginPage");
        }

Is there any other way to check session (authorization) globally and redirect to login page(Action)? Is this possible via Layout file? Like i'll create a common header layout to all the pages which will be accessed by logged in users so in that header layout is it possible to check for the session(authorization) and redirect to the login page (if not logged in) ?

You can simplify populating each action by having a "Base" controller decorated with [Authorize] attribute, and then other controllers inheriting from it. This will make authorization be persisted to "child" controllers and their actions. This however becomes problematic when you want to implement roles in membership where different actions have different roles.

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