Tip: ASP. NET MVC4: (6) Global filter, asp. netmvc4
Original article: http://blog.csdn.net/zx13525079024/article/details/19161777
The global filter in Asp. Net MVC4 can monitor the whole project globally.
Create an MVC4 project. You can see the following code in the global. asax file: FilterConfig. RegisterGlobalFilters (GlobalFilters. Filters );
Indicates registering a global filter.
GlobalFilters is a set of global filters. You can add a filter using the add method. By default, the HandleErrorAttribute filter is added to the set.
Next, create a custom filter and add it to the global filter set.
1. Create a custom filter
To create a custom filter, you must inherit the ActionFilterAttribute class. We create a filter named mermerfilterattribute and record the time in the action.
The Code is as follows:
[Csharp]View plaincopy
- Public class CustomerFilterAttribute: ActionFilterAttribute
- {
- Public override void OnActionExecuting (ActionExecutingContext filterContext)
- {
- Base. OnActionExecuting (filterContext );
- FilterContext. HttpContext. Response. Write ("Start Time:" + DateTime. Now. ToString () + "<br/> ");
- }
- Public override void OnActionExecuted (ActionExecutedContext filterContext)
- {
- Base. OnActionExecuted (filterContext );
- Var controllerName = filterContext. RouteData. Values ["controller"]. ToString ();
- Var actionName = filterContext. RouteData. Values ["action"]. ToString ();
- FilterContext. HttpContext. Response. Write ("End Time:" + DateTime. Now. ToString () + "<br/> ");
- FilterContext. HttpContext. Response. Write ("controller:" + controllerName + ", action:" + actionName );
- }
- }
2. Register a global Filter
After the filter is created, we Add the filter to the global filter and use filters. Add (new CustomerFilterAttribute (); method,
The Code is as follows:
[Csharp]View plaincopy
- Public class FilterConfig
- {
- Public static void RegisterGlobalFilters (GlobalFilterCollection filters)
- {
- Filters. Add (new HandleErrorAttribute ());
- Filters. Add (new CustomerFilterAttribute ());
- }
- }
Next we run each page of the project, and we will see the output time and controller name in the page, as shown below: