Actionfilter of asp.net core MVC filter (2)

Time:2021-5-9

This class will explain the use of built-in filter in asp.net core MVC, which is divided into the following chapters

  Exceptionfilter of asp.net core MVC filter (1)

Actionfilter of asp.net core MVC filter (2)

Resultfilter of asp.net core MVC filter (3)

Resourcefilter of asp.net core MVC filter (4)

Authorization filter of asp.net core MVC filter (5)

brief introduction

The action filter will execute the corresponding method before and after the action of the controller is executed.

Implement a custom action filter

Custom a global exception filter needs to be implementedIactionfilter interface

public class ActionFilter : IActionFilter
{
  public void OnActionExecuted(ActionExecutedContext context)
  {
    Console. Writeline ("after action execution");
  }

  public void OnActionExecuting(ActionExecutingContext context)
  {
    Console. Writeline ("before action execution");
  }
}

Iactionfilter needs to implement two methods, onactionexecuted and onactionexecuting. Onactionexecuting will be executed before action and onactionexecuted after action.

After knowing the principle, we can use its features to simplify our code. An important concept in MVC is model validation. We define model constraints, and then verify whether the model is bound successfully in the action. In our action, we repeatedly write the following code

[HttpGet]
public ActionResult Get()
{
  if (! Modelstate. Isvalid) return badrequest ("parameter error!");
}

This kind of repeated code not only increases the complexity of the code, but also is not beautiful. We can automatically complete it 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 binding error occurs, we throw the exception information, catch it in the exception filter in the previous chapter, and return the error information to the requester.

We can also use the feature of actionfilter to record the execution time of an action, and output a warning log when the execution time of an action 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: {time. Tostring()}");
    }
  }

  public void OnActionExecuting(ActionExecutingContext context)
  {
    var stopwach = new Stopwatch();
    stopwach.Start();
    context.HttpContext.Items.Add(Resources.StopwachKey, stopwach);
  }
}

The above code uses httpcontext to pass a stopwatch to calculate the execution time of the action, and outputs the warning log when it exceeds 5 seconds.

Register global filters

The registration method is the same as exceptionfinder. Find the system root directory startup.cs file and modify the configuration services as follows


services.AddMvc(options =>
      {
        options.Filters.Add<ActionFilter>();
      });

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.