Executing code before any action
Asked Answered
A

2

16

I have the following requirement:

On every request to my web page, regardless of which action the user is trying to invoke, I need to call some code that checks if a resource is in place. If it is, then everything is fine and the action method should be called as normal.

However, if this resource is not available, I want all requests to return a separate page asking the user to select another resource from a list of available ones.

So is it possible to have one method run before any action method that have the option of cancelling the call to the action method, and doing something else instead?

Administrative answered 3/1, 2012 at 7:33 Comment(3)
You could implement your own HttpModule, or perhaps put your check in Application_BeginRequest() inside global.asax.csKone
One more option is to use a custom middleware, which allows you to fine tune when exactly your code gets to run: learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…Agile
@MladenB. Middleware is a Core thing. I assume from the tags this is not.Forth
S
24

Look at global action filters (available since asp.net mvc 3): http://msdn.microsoft.com/en-us/library/gg416513%28v=vs.98%29.aspx

Basically, in your Global.asax, you can register the filter globally during your application startup (in Application_Start()) with:

GlobalFilters.Filters.Add(new MyActionFilterAttribute());

You can then override the OnActionExecuting method, and set the Result property with a RedirectToRouteResult.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (IsMyResourceAvailable())
    {
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary {
                { "Controller", "YourControllerName" },
                { "Action", "YourAction" } 
            });
    }

    base.OnActionExecuting(filterContext);
}
Saintly answered 3/1, 2012 at 7:45 Comment(1)
Its not right answer. This method get called when action is executing. And how one would know about like accessing IsMyResourceAvailable in action method and calling it in filter. i.e. If user is not authenticated and use Id for accessing db record then how to check this in action filter. Not right answerUngual
S
8

MVC provides several hooks to do this.

In a base controller, you can override Controller.OnActionExecuting(context) which fires right before the action executes. You can set context.Result to any ActionResult (such as RedirectToAction) to override the action.

Alternatively, you can create an ActionFilterAttribute, and exactly like above, you override the OnActionExecuting method. Then, you just apply the attribute to any controller that needs it.

Superfluid answered 3/1, 2012 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.