asp.net ActionFilter filter

巴扎黑
Release: 2017-09-01 14:41:37
Original
1688 people have browsed it

This article mainly introduces the ActionFilter filter of asp.net core MVC filter in detail, which has certain reference value. Interested friends can refer to it

This series of classes will Explaining the use of built-in filters in asp.net core MVC will be divided into the following chapters

 asp.net core MVC filter ExceptionFilter filter (1)

 asp.net core MVC Filter's ActionFilter filter (2)

 asp.net core MVC filter's ResultFilter filter (3)

 asp.net core MVC filter's ResourceFilter filter (4)

 asp.net core MVC filter AuthorizationFilter filter (5)

Introduction

The Action filter will be executed before and after the controller's Action Execute the corresponding method.

Implementing 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("action执行之后");
  }

  public void OnActionExecuting(ActionExecutingContext context)
  {
    Console.WriteLine("action执行之前");
  }
}
Copy after login

IActionFilter needs to implement two methods, OnActionExecuted and OnActionExecuting. OnActionExecuting will be executed before Action and OnActionExecuted will be executed after Action.

After knowing the principle, we can use its features to simplify our code. An important concept in MVC is Model verification. We define Model constraints, and then verify whether the Model is successfully bound in Action. Repeatedly write the following code in our Action


[HttpGet]
public ActionResult Get()
{
  if (!ModelState.IsValid) return BadRequest("参数错误!");
}
Copy after login

Such repeated code not only increases the complexity of the code but is also unsightly. 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);
}
Copy after login

When the Model binding error occurs, we throw exception information, capture it in the exception filter ExceptionFilter in the previous chapter, and return the error information to the requester.

We can also use the features of ActionFilter to record the execution time of the 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}执行耗时:{time.ToString()}");
    }
  }

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

Use the above code Use HttpContext to pass a Stopwach to calculate the execution time of the action and output a warning log if it exceeds 5 seconds.

Register global filter

The registration method is the same as ExceptionFinter. Find the Startup.cs file in the system root directory and modify the ConfigureServices method as follows


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

The above is the detailed content of asp.net ActionFilter filter. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!