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?
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns. Result filters contain logic that is executed before and after a view result is executed.
ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.
Filters in ASP.NET Core allow code to run before or after specific stages in the request processing pipeline. Built-in filters handle tasks such as: Authorization, preventing access to resources a user isn't authorized for. Response caching, short-circuiting the request pipeline to return a cached response.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With