Document directory
- Preface
- Section 1: Knowledge reserves
- Section 2: Filter practices
- The following describes the filters of several systems.
Preface
When developing large projects, there will always be related AOP-oriented cross-section programming components, while MVC (especially: Asp.. Net MVC, all of which are the same below) the project does not want MVC developers to care about and write repeated Code such as identity authentication, logs, exceptions, and behavior interceptions, we can implement it through AOP intercept, and in the MVC project, we can directly use the Filter feature provided by it to help us solve the problem, without the need to implement complicated AOP by ourselves.
In Asp.net Mvc, you can use the Filter function when you have the following and similar requirements:
- Determine logon or User Permissions
- Decision output Cache
- Anti-leech
- Anti-spider
- Localization and internationalization settings
- Implement Dynamic Action
Section 1: Knowledge reserves
Asp. Net MVC provides the following default filters:
Filter Type
Implementation Interface
Execution time
Default Implementation
Authorization filter
IAuthorizationFilter
Execute before all filters and actions are executed.
AuthorizeAttribute
Action filter
IActionFilter
Before and after the Action is executed, respectively.
ActionFilterAttribute
Result filter
IResultFilter
After the Action Result is executed and before
ResultFilterAttribute
Exception filter
IExceptionFilter
Only in filter,
Or action method, or action result is executed when an exception is thrown
HandleErrorAttribute
Note that ActionFilterAttribute provided by Asp. Net MVC implements IActionFilter and IResultFilter by default. ActionFilterAttribute is an Abstract type, so it cannot be used directly. Because it cannot be instantiated, We must inherit it before using it.
Filters inherit from ActionFilterAttribute abstract classes and can overwrite void OnActionExecuting (ActionExecutingContext), voidOnActionExecuted (ActionExecutedContext), void aggregate (ResultExecutingContext), and aggregate (ResultExecutedContext ).
Their execution order is as follows:
OnActionExecuting is the operation before the Action is executed.
OnActionExecuted indicates the operation after the Action is executed.
OnResultExecuting is executed before parsing ActionResult
OnResultExecuted is executed after the ActionResult is parsed.
Next, we only need to rewrite the above method to perform some operations in the corresponding steps.
Section 2: Filter practices
I would like to give you an example below to show the execution sequence of the fake scripts.
First, add a common class that inherits the ActionFilterAttribute and directly runs the code.
Public class TestFilterAttribute: ActionFilterAttribute {public string Message {get; set;} public override void OnActionExecuting (ActionExecutingContext filterContext) {base. onActionExecuting (filterContext); filterContext. httpContext. response. write ("before the Action is executed" + Message + "<br/>");} public override void OnActionExecuted (ActionExecutedContext filterContext) {base. onActionExecuted (filterContext); filterContext. httpContext. response. write ("after the Action is executed" + Message + "<br/>");} public override void OnResultExecuting (ResultExecutingContext filterContext) {base. onResultExecuting (filterContext); filterContext. httpContext. response. write ("before the Result is returned" + Message + "<br/>");} public override void OnResultExecuted (ResultExecutedContext filterContext) {base. onResultExecuted (filterContext); filterContext. httpContext. response. write ("after Result is returned" + Message + "<br/> ");}}
After writing this code, we will return to the Action and mark it as follows:
[TestFilter (Message = "Action")] public ActionResult Index () {HttpContext. response. write ("Action is being executed... <br/>"); return Content ("Result is being returned... <br/> ");}
Then access the preceding Action in the browser to see the following execution sequence.
The overall execution sequence is:
Before an Action is executed: The OnActionExecuting method is executed first → Action execution → OnActionExecuted method execution → OnResultExecuting method execution → executeResult method execution in the returned ActionRsult → OnResultExecuted execution. The final result is shown in.
It feels great! Haha! To use this filtering mechanism, you only need to add a tag on the Action to achieve the effect.
If we call this tag to the Controller, TestFilterAttributeFilter will use all the actions under the Controller. The following code is used:
[TestFilter (Message = "Controller")] public class TestFilterController: Controller {// GET:/TestFilter/[TestFilter (Message = "Action")] public ActionResult Index () {HttpContext. response. write ("Action is being executed... <br/>"); return Content ("Result... returned <br/> ");}}
If we simply follow the code above, there is a problem. What will happen when we execute the displayed page? Will the Filter on the Controller be executed? Will the tag function be executed twice? The final execution result is shown below:
Result Description: The TestFilterAttribute label is applied to the Action by default. Although this label is also applied to the Controller, only the tag on the Action takes effect.
Supplement: if the Action is not labeled with TestFilterAttribute, the tag on the Controller will be executed.
When the Index is executed, the Filter method is executed only once. In some cases, we also want the FilterAttribute on the Controller to execute TestFilterAttribute once, then how can we make the [TestFilter (Message = "Controller")] on the controller take effect?
The answer is:We only need to mark [AttributeUsage (AttributeTargets) on the definition of the TestFilterAttribute class. all, AllowMultiple = true)] You can [the top red font of the lower class], that is, make it an Action that can be executed multiple times..The Code is as follows:
[AttributeUsage (AttributeTargets. all, AllowMultiple = true)] public class TestFilterAttribute: ActionFilterAttribute {public string Message {get; set;} public override void OnActionExecuting (ActionExecutingContext filterContext) {base. onActionExecuting (filterContext); filterContext. httpContext. response. write ("before the Action is executed" + Message + "<br/>");} public override void OnActionExecuted (ActionExecutedContext filterContext) {base. onActionExecuted (filterContext); filterContext. httpContext. response. write ("after the Action is executed" + Message + "<br/>");} public override void OnResultExecuting (ResultExecutingContext filterContext) {base. onResultExecuting (filterContext); filterContext. httpContext. response. write ("before the Result is returned" + Message + "<br/>");} public override void OnResultExecuted (ResultExecutedContext filterContext) {base. onResultExecuted (filterContext); filterContext. httpContext. response. write ("after Result is returned" + Message + "<br/> ");}}
The browsing effect is as follows:
The result is:ActionFilter on Controller prior to ActionMark execution on. Similarly, before the Result executes the executeResult method, the OnResultexecuteing method in the Filter tag on the Controller is first executed.
The execution sequence is as follows:OnActionExecuting on the Controller → OnActionExecuting on the Action → Action execution → OnActionExecuted on the Action → OnActionExecuted on the Controller
At this point, the Action is executed. We can see that it is an order of inbound and outbound stack. The Action returns the ActionResult and executes the ExecuteResult method. However, Filter is executed before execution. The specific sequence is as follows:
Connection →The OnResultExecuting method of the Controller → OnResultExecuting on the Action → the Action returns the ActionResult and executes the ExecuteResult method → OnResultExecuted execution on the Action → OnResultExecuted execution on the Controller → end.
Another problem arises. We think that some public methods need to execute the following for each Action, and it is very painful to mark all controllers. Fortunately, Asp. Net MVC3 brings a wonderful thing, global Filter. How can I register a global Filter? The answer is in Global. asax. Let's take a look at the following code: How can I register the TestFilterAttribute defined above to the global Filter. Code:
Public static void RegisterGlobalFilters (GlobalFilterCollection filters) {filters. add (new handleerrorattriters (); // register the global filter filters. add (new TestFilterAttribute () {Message = "Global "});}
The effect is as follows:
We can see that the global Action is first executed, then the Filter execution under the Controller, and finally the tag execution on the Action. Of course, this is the premise of marking [AttributeUsage (AttributeTargets. All, AllowMultiple = true)] on the definition of the TestFilterAttribute class. Otherwise, if the Action is tagged with the same Controller, it will only execute the Filter on the Action.
The following describes the filters of several systems.
Iii. AcceptVerbs
Specifies the access form of the page, such
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Example(){
return View();
}
Pages can only be accessed in the form of Post, that is, form submission.
Iv. ActionName
Specifies the name of the Action.
Application Scenario: if you do not want to use the method name as the Action name or the Action name as the keyword, for example
[ActionName("class")]
public ActionResult Example(){
return View();
}V. NonAction
The current method is only a common method and is not parsed as an Action.
Vi. OutputCache
Add cache for Action
[OutputCache(Duration = 60, VaryByParam = "*")]
public ActionResult Example()
{
return View();
}
VII. ValidateInput
This Action can accept Html and other dangerous code (ASP. net mvc cannot complete equivalent tasks by setting the <% @ Page attribute in aspx .)
[ValidateInput(false)]
public ActionResult Example()
{
return View();
}
8. ValidateAntiForgeryTokenAttribute
Used to verify server tampering.
[ValidateAntiForgeryToken]
public ActionResult Example()
{
return View();
}
Summary
This article introduces how to use filters and how to use global filters, especially when the same Filter repeats the same Action, if the tag that can be executed multiple times is not set, only the Filter on the Action is executed, while the Controller and global Filter are blocked, but the setting can be executed multiple times, first, execute the global Filter, then the Controller, and then the Filter on the Action. We also learned how to use the system Filter.
Author: boruipower
Source: http://www.cnblogs.com/boruipower