Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ActionFilter filter in asp.net

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use the ActionFilter filter in asp.net. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Brief introduction

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

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 execution");}}

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

Once we know 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 binding is successful in Action. We repeat the following code in our Action

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

This repetitive code not only increases the complexity of the code, but also makes it unattractive, which can be done 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 an Model binding error occurs, we throw an exception message, catch it in the exception filter ExceptionFilter in the previous chapter, and return the error message to the requester.

We can also use the features of ActionFilter to record the execution time of Action, and output warning logs 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 (); var logger = factory.CreateLogger (); 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 Stopwach to calculate the execution time of the action and outputs a warning log when it exceeds 5 seconds.

Register a global filter

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

Services.AddMvc (options = > {options.Filters.Add ();}); this is the end of the article on "how to use ActionFilter filters in asp.net". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report