1
votes

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) ?

1
use Authorize attribute. asp.net/web-api/overview/security/…ramiramilu
You can take a look at this : Form Authentication in ASP.NET MVC codeproject.com/Articles/578374/…Edward N
@trungtin1710 thanks for the useful link , is it possible via Layout file ? like i will 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)?MAK
@MAK that's what the Authorize attribute mentioned by @ramiramilu does. That code project linked article is old, and the way to go today is to use asp.net/identityBrendan Green

1 Answers

0
votes

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.