MVC and Web API filters, mvcfilter
MVC and Web API Filter)
ASP. net mvc supports the following types of operation filters:
· Authorization filter. These filters are used to implement IAuthorizationFilter and to make security decisions about whether to perform operation methods (such as performing identity authentication or verifying request attributes. The AuthorizeAttribute class and RequireHttpsAttribute class are examples of authorization filters. The authorization filter runs before any other filters.
· Operation filter. These filters are used for IActionFilter and packaging operation method execution. The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted. OnActionExecuting runs before the operation method. OnActionExecuted runs after the operation method. You can perform other operations, such as providing additional data to the operation method, checking the return value, or canceling the operation method.
· Result filter. These filters are used to implement IResultFilter and to encapsulate the execution of ActionResult objects. IResultFilter declares two methods: OnResultExecuting and OnResultExecuted. OnResultExecuting runs before executing the ActionResult object. OnResultExecuted runs after the result. You can perform other processing operations on the result, such as modifying the HTTP response. The OutputCacheAttribute class is an example of a result filter.
· Exception filter. These filters are used to implement IExceptionFilter and are executed when an unhandled exception is thrown during the execution of the ASP. net mvc pipeline. An exception filter can be used to execute tasks such as logging or displaying error pages. The handleerrorattri class is an example of an exception filter.
Different types of filters
The ASP. net mvc Framework supports four different types of filters:
Note:
In MVC, the filter is implemented by system. web. Mvc. dll.
Implement Global filter: In the FilterConfig. cs file under the App_Start folder
Public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
// New Test_Mvc.Mvc_Filter () Instance Object of the filter class
Filters. Add (new Test_Mvc.Mvc_Filter (); // -- register the global filter.
}
System. Web. http. Filters in the system. web. http. dll filter in web APIs must be set to an empty Api controller. If an empty MVC controller is selected, the filter fails.
Implement Global filter: Global. asax file:
Protected void Application_Start ()
{
// New Test_Http.Http_Filter () Instance Object of the filter class
GlobalConfiguration. Configuration. Filters. Add (newTest_Http.Http_Filter (); // -- register a global Filter
}