Home Backend Development C#.Net Tutorial asp.net ActionFilter filter

asp.net ActionFilter filter

Sep 01, 2017 pm 02:41 PM
asp.net filter

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue error: The filter in filters cannot be used correctly, how to solve it? Vue error: The filter in filters cannot be used correctly, how to solve it? Aug 26, 2023 pm 01:10 PM

Vue error: The filter in filters cannot be used correctly, how to solve it? Introduction: In Vue, filters are a commonly used function that can be used to format or filter data. However, during use, sometimes we may encounter problems with not being able to use the filter correctly. This article will cover some common causes and solutions. 1. Cause analysis: The filter is not registered correctly: Filters in Vue need to be registered before they can be used in templates. If the filter is not successfully registered,

How to filter and sort data in Vue technology development How to filter and sort data in Vue technology development Oct 09, 2023 pm 01:25 PM

How to filter and sort data in Vue technology development In Vue technology development, data filtering and sorting are very common and important functions. Through data filtering and sorting, we can quickly query and display the information we need, improving user experience. This article will introduce how to filter and sort data in Vue, and provide specific code examples to help readers better understand and use these functions. 1. Data filtering Data filtering refers to filtering out data that meets the requirements based on specific conditions. In Vue, we can pass comp

In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs In PHP, the FILTER_VALIDATE_URL constant represents the filter used to validate URLs Sep 14, 2023 am 10:37 AM

The FILTER_VALIDATE_URL constant is used to validate URLs. The flag FILTER_FLAG_SCHEME_REQUIRED−URL must be RFC compliant. FILTER_FLAG_HOST_REQUIRED−URL must contain the hostname. FILTER_FLAG_PATH_REQUIRED−URL must have a path after the domain name. FILTER_FLAG_QUERY_REQUIRED−URL must have a query string. Return value FILTER_VALIDATE_URL

Filter function in Vue3: handle data elegantly Filter function in Vue3: handle data elegantly Jun 18, 2023 pm 02:46 PM

Filter Functions in Vue3: Handling Data Elegantly Vue is a popular JavaScript framework with a large community and a powerful plug-in system. In Vue, the filter function is a very practical tool that allows us to process and format data in templates. There have been some changes to the filter functions in Vue3. In this article, we will take a deep dive into the filter functions in Vue3 and learn how to use them to handle data gracefully. What is a filter function? In Vue, the filter function is

PHP Email Filter: Filter and identify spam. PHP Email Filter: Filter and identify spam. Sep 19, 2023 pm 12:51 PM

PHP Email Filter: Filter and identify spam. With the widespread use of email, the amount of spam has also continued to increase. For users, the amount of spam they receive can lead to information overload and wasted time. Therefore, we need an efficient method to filter and identify spam emails. This article will show you how to write a simple but effective email filter using PHP and provide specific code examples. Basic Principle of Email Filter The basic principle of email filter is to determine whether the email is

Tips for using plug-ins to implement custom filters in Vue Tips for using plug-ins to implement custom filters in Vue Jun 25, 2023 pm 05:01 PM

Tips for using plug-ins to implement custom filters in Vue Vue.js provides a convenient way to handle the need for view data filtering, that is, filter. Filters are mainly responsible for formatting and processing the data in the view to make the data more intuitive and easy to understand. Vue has some built-in commonly used filters, such as date formatting, currency formatting, etc., and also supports custom filters. This article will introduce how to use the Vue plug-in to implement custom filters and provide some practical filtering techniques.

Several methods to solve Tomcat garbled code Several methods to solve Tomcat garbled code Dec 28, 2023 pm 01:32 PM

Several methods to solve the problem of Chinese garbled characters in Tomcat, which require specific code examples. In web development, we often encounter the problem of Chinese garbled characters in Tomcat. This problem will cause garbled characters or appear as boxes, question marks and other characters when processing Chinese characters, bringing a bad experience to users. In order to solve this problem, this article will introduce several commonly used methods and provide specific code examples. Modify the Tomcat configuration file. Find the conf/server.xml file in the Tomcat installation directory and search for the default

How to implement data filtering and sorting for RESTful API in PHP How to implement data filtering and sorting for RESTful API in PHP Sep 05, 2023 pm 01:12 PM

How to implement RESTfulAPI data filtering and sorting in PHP With the continuous development of web applications, RESTfulAPI has become one of the commonly used data interaction methods in modern applications. In the REST architecture, the design and implementation of APIs need to take into account the filtering and sorting of data in order to return data that meets user needs. This article will introduce how to implement the data filtering and sorting functions of RESTfulAPI in PHP, with code examples. 1. Data filtering in RESTfu

See all articles