Reputation: 6531
I have an ASP.NET MVC application and I want to be able to perform some logic 'just once' per page request. More specifically, I need to check details surrounding the logged in users role 'just once', each time they request a page within the application. I need to check the DB to see if their role has been changed since (flag in the db) and if so, log them out and redirect them back to the login screen.
I started off by creating a Base Controller and putting this logic inside the base class Initialize method, which works fine. The problem is that this particular initialize code is getting fired multiple times per page request (as there are numerous controllers in the application, many of which can get instantiated with any given page request.
I only want/need my logic (currently inside the base controller Initialize method) to occur once per page request though.
What approach would be recommended for this?
Upvotes: 2
Views: 437
Reputation: 3024
BaseController
is the right place. You need to use OnActionExecuting
filter. override it in BaseController, and put logic inside
roughly like:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(roleChanged)
{
context.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Home",
action = "Logout"
}));
}
}
You can further utilize filterContext
instance to place checks on specific calls by determining Action
and Controller
for each request. (eg, i usually need this in case of ajax
call)
Upvotes: 2
Reputation: 1416
Filter ajax request and child actions in base controller in Initialize method.
protected override void Initialize(RequestContext requestContext) {
if (requestContext.HttpContext.Request.IsAjaxRequest() || ControllerContext.IsChildAction)
return;
}
Upvotes: 1
Reputation: 4628
You can create an action filter (https://msdn.microsoft.com/en-us/library/gg416513%28VS.98%29.aspx) and override the OnActionExecuting method.
In it you only execute your logic if: - it is a GET - it is not an AJAX initiated request
Upvotes: 2