Subin Jacob
Subin Jacob

Reputation: 4864

Check Session for all Controllers?

After user logged in, a session will be set. I want to check the user session in all controllers (not all, but controllers which require a logged in user). In webforms we could do it in the page_load or using base classes. What's the recommended approach in asp mvc to do this? (I saw it would be a bad idea to use base controllers)

Upvotes: 2

Views: 3447

Answers (2)

Simon Holman
Simon Holman

Reputation: 150

There are 2 ways to do this.

You could create a custom authorization attribute inheriting from AuthorizeAttribute and do all your session and authorization code in one place, or

You could create your own Action Filter that does the necessary session checking and attach both attributes to the actions/controllers.

It depends on whether you would either want one or the other of these pieces of functionality to operate independently, if so, opt for the latter suggestion.

Upvotes: 1

Amit
Amit

Reputation: 15387

You can create a controller (check session in this) with inherit by base controller and refer this controller into your required controller.

BaseController:

 public class BaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //check Session here
        }
    }

DerivedController:

 public class ABCController : BaseController
    {
       //Your code
    }

Upvotes: 1

Related Questions