The Actionfilter filter for ASP.

Source: Internet
Author: User
This article is mainly for you to introduce the ASP. NET Core MVC filter Actionfilter filter, with a certain reference value, interested in small partners can refer to

This department class will explain the use of built-in filters in ASP. NET core MVC, which will be divided into the following chapters

Exceptionfilter filter for ASP. NET Core MVC filter (i)

ASP. NET Core MVC filter Actionfilter filter (ii)

ASP. NET Core MVC filter Resultfilter filter (iii)

Resourcefilter filter for ASP. NET Core MVC filter (iv)

ASP. NET Core MVC filter Authorizationfilter filter (v)

Brief introduction

The action filter executes the appropriate method before and after the Controller's action is executed.

Implement a custom action filter

Customizing a global exception filter requires implementing the Iactionfilter interface


public class actionfilter:iactionfilter{public  void onactionexecuted (ActionExecutedContext context)  {    Console.WriteLine ("After Action execution");  }  public void onactionexecuting (ActionExecutingContext context)  {    Console.WriteLine ("Before Action executes");}  }

Iactionfilter need to implement two methods onactionexecuted,onactionexecuting. OnActionExecuting will be executed before the action, onactionexecuted after the action.

Knowing the principle, we can use its features to simplify our code, an important concept in MVC is the model validation, we define the model constraint, and then verify in action that the model is bound successfully, and our action repeatedly writes the following code


[Httpget]public actionresult Get () {  if (! Modelstate.isvalid) return badrequest ("parameter wrong!");}

This repetitive code not only adds to the complexity of the code, but we can do it automatically in Actionfilter.


public void onactionexecuting (ActionExecutingContext context) {  if (context. Modelstate.isvalid) return;  var modelstate = context. Modelstate.firstordefault (f = f.value.errors.any ());  String errormsg = ModelState.Value.Errors.First (). errormessage;  throw new Appexception (errormsg);}

When the model is bound to an error, we throw an exception message and catch it in the exception filter exceptionfilter in the previous section, returning an error message to the requester.

We can also use the Actionfilter feature to record the execution time of an action and output a warning log when the action execution time is too slow


public class actionfilter:iactionfilter{public  void onactionexecuted (ActionExecutedContext context)  {    var HttpContext = context. HttpContext;    var Stopwach = Httpcontext.items[resources.stopwachkey] as Stopwatch;    Stopwach. Stop ();    var time = Stopwach. Elapsed;    if (time. TotalSeconds > 5)    {      var factory = context. Httpcontext.requestservices.getservice<iloggerfactory> ();      var logger = factory. Createlogger<actionexecutedcontext> ();      Logger. Logwarning ($ "{context. Actiondescriptor.displayname} Execution time: {. ToString ()} ");    }  }  public void onactionexecuting (ActionExecutingContext context)  {    var stopwach = new Stopwatch ();    Stopwach. Start ();    Context. HTTPCONTEXT.ITEMS.ADD (Resources.stopwachkey, Stopwach);}  }

The code above uses HttpContext to pass a stopwach to calculate the execution time of the action and output a warning log for more than 5 seconds.

Registering a global filter

The registration method is the same as Exceptionfinter. Locate the system root Startup.cs file and modify the Configureservices method as follows


Services. ADDMVC (options =        options. Filters.add<actionfilter> ();      });
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.