What are action filters?
Action Filters are custom classes that provide pre-action and
post-action behavior to the controllers action methods. This is a good
thing because you may be in a situation when you need some logic to be
performed before or after action execution.
Provided filter types in MVC 5
Override filter
Override filter is a new filter type that is used
for indicating which filters need to be overridden. When creating a
custom override filter you have to implement implement IOverrideFilter as well to declare and implement the FiltersToOverride property. See below:
public class CustomOverrideFilter : FilterAttribute, IOverrideFilter
{
public Type FiltersToOverride
{
get
{
//This property is responsible for returning the filter that needs to be overridden.
//For example:
return typeof (IActionFilter);
}
}
}
You can read more regarding the new MVC 5 filter override in this post “How to use the ASP.NET MVC 5 Filter Overrides Feature”
Authentication filter
New authentication filter makes security decisions if the action
should be executed or not by validating the user authentication request.
Also it is responsible for updating the Principle. This is also a new
filter that was released with MVC 5. While creating a custom
authentication filter you have to implement IAuthenticationFilter plus declare and implement the OnAuthentication and OnAuthenticationChallenge methods. See below:
public class CustomAuthenticatioFilter : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
//This method is responsible for setting and modifying the principle for the current request though the filterContext .
//Here you can modify the principle or applying some authentication logic.
//filterContext.Principal = ...;
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//This method is responsible for validating the current principal and permitting the execution of the current action/request.
//Here you should validate if the current principle is valid / permitted to invoke the current action. (However I would place this logic to an authorization filter)
//filterContext.Result = new RedirectToRouteResult("CustomErrorPage",null);
}
}
More regarding the new authentication filter you can find in this post “Finally the new ASP.NET MVC 5 Authentication Filters!”.
Authorization filter
Authorization filter is also responsible for making security
decisions if the action should be executed or not by validating whether
the user is authorized by a given criteria or validating the requests
properties. While creating a custom authorization filter you have to
implement the IAuthorizationFilter, declare and implement OnAuthorization. See below:
public class CustomAuthorizationFilter : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
//This method is responsible for validating the user or properties (authentication/authorization ) and checking if he as authorization
//access to the action / controller or system (if the custom authorization filter is registered as a global filter)
//The user can be validate by the role or some authorization criteria that needs to be applied.
}
}
When to use:
Lets say that you have pages or actions in your web application that
can be executed only by authorized user that have a specific role. This
is a good fit to use the Authorize filter attribute and specify it Roles parameter.
Another reason touse it is when you have pages or actions that can be
accessed only by authorized users that get redirected or linked by a
specific URL. Here you have to create a custom authorization filter:
validate if the user is authorized and check that the HttpContext.Request.UrlReferrer is a valid URL.
Action filter
Action filter is responsible for performing additional logic before
and after the controllers action execution. When creating a custom
action filter you have to implement the IActionFilter, declare and implement OnActionExecuting and OnActionExecuted methods. See below:
public class CustomActionFilter : FilterAttribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
//This method gets invoked before action execution.
//Here you can perform different operation from validating properties, adding additional properties to the context,
//perform some additional operation even do a redirect if needed and so on.
//In general here you will have logic that needs to be performed before action execution
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
//This method get invoked after action execution.
//Here you can perform the same things as in the OnActionExecuting method,
//the only different is that here you will be placing logic that needs to be performed before action execution.
//Note: the filterContext.Canceled is TRUE if you change the Result to another in the OnActionExecuting method.
filterContext.Canceled == true;
}
}
When to use:
Action filter is really a great thing because during the OnActionExecuting the filterContext
parameter, that passed to the method, has a lot of information about
the current context. You can use this information to perform logic or
you can manipulate and change the context according to your logic needs.
Action filters can be used to audit and log user activities on a set of actions or controllers or the whole application.
Result filter
Result filter is responsible for performing additional logic before
and after action result execution. To create a custom result filter
you’ll have to implement IResultFilter, declare and implement OnResultExecuting and OnResultExecuted. See below:
public class CustomResultFilter : FilterAttribute, IResultFilter
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
//This method gets invoked before the ActionResult is executed.
//Here you can perform different operations like validate the action result that will be returned to the user,
//replace the action result, add additional extra metadata to the HTTP context,
//Note: You can cancel ActionResult execution by setting by setting
filterContext.Cancel = true;
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
//This method gets invoked after the Action is executed.
//Here you can't update or change action result because it has already been executed.
//However you can still write to the Http response / context.
//Note: Indicated that the ActionResult execution was canceled (the cancelation can be done in OnResultExecuting):
filterContext.Canceled;
}
}
When to use:
One good example that comes into mind is changing the model that is
being returned to a view model using AutoMapper or other mapping lib
that you prefer. Another example is changing the result if we have an
invalid model or an invalid result to redirect to an error page. And
more…
Exception filter
Exception filter is responsible for handling errors that are raised
by the action or action results. To create a custom exception handler
you have to implement the IExceptionFilter interface, declare and implement its OnException method. See below:
public class CustomException : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
//This method gets invoked after all other filter have been executed and if an exception occurred during method execution.
//Here you should place logic to handle the exception the way you need.
}
}
When to use:
Use this filter to log the exception or to redirect to another
action. You may handle the exception in your application the way you
need.
That’s it!
We have covered all available filter types that are provided in MVC 5
and now have a glance look how to create a custom filter of each type.
Reference:http://hackwebwith.net/asp-net-mvc-5-action-filter-types-overview/