asp. net core MVC Filter of 2

  • 2021-10-13 07:12:37
  • OfStack

This class will explain the use of built-in filters in asp. net core MVC and will be divided into the following sections

asp. net core MVC Filter ExceptionFilter Filter (1)

asp. net core MVC filter ActionFilter filter (2)

asp. net core MVC filter ResultFilter filter (3)

asp. net core MVC Filter ResourceFilter Filter (4)

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

Brief introduction

The Action filter executes the corresponding methods before and after Action execution of controller.

Implement a custom Action filter

To customize a global exception filter, you need to implement IActionFilter interface


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

  public void OnActionExecuting(ActionExecutingContext context)
  {
    Console.WriteLine("action Before execution ");
  }
}

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

After we know the principle, we can use its characteristics to simplify our code. One important concept in MVC is Model verification. We define Model constraints, and then verify whether Model is bound successfully in Action. In our Action, we repeatedly write the following code


[HttpGet]
public ActionResult Get()
{
  if (!ModelState.IsValid) return BadRequest(" Parameter error !");
}

This repetitive code not only increases the complexity of the code, but also is not beautiful. 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 Model binds incorrectly, we throw an exception message, which is captured in the exception filter ExceptionFilter in the previous chapter, and returns the error message to the requester.

We can also use the characteristics of ActionFilter to record the execution time of Action, and output warning log when the execution time of 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 consuming :{time.ToString()}");
    }
  }

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

The above code calculates the execution time of action by passing one Stopwach using HttpContext, and outputs a warning log when it exceeds 5 seconds.

Register global filters

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


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

Related articles: