当前位置:网站首页>ASP. Net core actionfilter filter details
ASP. Net core actionfilter filter details
2022-07-26 04:20:00 【Roman Sultan Mohammed】
ActionFilter yes ASP.NET CORE Provide a method filter or interceptor
It is generally used to perform some operations before or after method execution (AOP)
The function is a bit similar to Spring Of Interceptor and AspectJ Provided AOP function ,
But there are several ways to implement , Let me introduce it
1. Realization IAcionFilter Interface , Override the method
IActionFilter Two methods need to be implemented OnActionExecuting,OnActionExecuted
They represent before method execution , And method implementation .
public class TestFilter : IActionFilter
{
// Call after execution of method
public void OnActionExecuted(ActionExecutedContext context)
{
throw new NotImplementedException();
}
// Call before execution of method
public void OnActionExecuting(ActionExecutingContext context)
{
throw new NotImplementedException();
}
}
Let's test it here
public class TheFirstFilter : IActionFilter
{
private readonly ILogger<TheFirstFilter> logger;
public TheFirstFilter(ILogger<TheFirstFilter> logger)
{
this.logger = logger;
}
public void OnActionExecuted(ActionExecutedContext context)
{
logger.LogInformation("Do something After Action");
}
public void OnActionExecuting(ActionExecutingContext context)
{
logger.LogInformation("Do something Before Action");
}
}
stay Services There are filters in the
services.AddMvc(option => {
option.Filters.Add(typeof(TheFirstFilter));
});
Create method
[HttpGet]
public string ActionFilterTestOne()
{
logger.LogInformation("The Action is Executing Now");
return "ActionFilterTestOne";
}
perform 
One .ActionExecutingContext Use
This is the parameter before the method execution , It and ActionExecutedContext Same inheritance FilterContext, But there are some differences
1. Cannot get the return value in the function before the corresponding method is executed
although ActionExecutingContext Provides result attribute , When you get , Will cause null pointer exception
reform Filter as follows .
public class TheFirstFilter : IActionFilter
{
private readonly ILogger<TheFirstFilter> logger;
public TheFirstFilter(ILogger<TheFirstFilter> logger)
{
this.logger = logger;
}
public void OnActionExecuted(ActionExecutedContext context)
{
logger.LogInformation("Do something After Action");
}
public void OnActionExecuting(ActionExecutingContext context)
{
// Try to get the return value of the method before the method executes
ObjectResult result = (ObjectResult)context.Result;
logger.LogInformation(result.Value.ToString());
}
}
When the interface is adjusted again, an error occurs 
2. It is very convenient to obtain method parameter values and types
ActionExecutingContext Provides a ActionArguments attribute , It is directly the name and value of the parameter Map type , Very easy to use
test :
public void OnActionExecuting(ActionExecutingContext context)
{
// Get the parameter name and value of the method
IDictionary<string, object> argsMap = context.ActionArguments;
foreach(KeyValuePair<string,object> pair in argsMap)
{
logger.LogInformation("Arg:" + pair.Key + " | Value:" + pair.Value);
}
}
Add some parameters to the called interface
[HttpGet]
public string ActionFilterTestOne(string paramOne,string paramTwo,string paramThree)
{
logger.LogInformation("The Action is Executing Now");
return "ActionFilterTestOne";
}

(PS: There are more ways to hang , Can be used to obtain parameters Type Information , Used to complete some more complex operations )
public void OnActionExecuting(ActionExecutingContext context)
{
// Get the parameter name and value of the method
IDictionary<string, object> argsMap = context.ActionArguments;
foreach(KeyValuePair<string,object> pair in argsMap)
{
// Can pass ActionExecutingContext and ActionExecutedContext All have ActionDescriptor.Parameters Get the type information of parameters in
logger.LogInformation
("Arg:" + pair.Key + " | Value:" + pair.Value + " | Type:" + context.ActionDescriptor.Parameters.Where(item=>item.Name==pair.Key).First().ParameterType);
}
}

3. Interrupt the execution of the method , The setting method is short circuited
It was said that ,ActionExecutingContext Can't get Result attribute ,
But it can be set Result attribute , Then through the empty return Short circuit the method , The method body of the call is no longer executed , End the request directly
This is done JWT The verifier of Filter Is widely practiced ,
Of course, it can also be used to verify Session
test :
public class TokenFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
string P1 = context.ActionArguments["paramOne"].ToString();
if (!P1.Equals("12345"))
{
context.Result = new JsonResult(" Method execution is shorted ");
// Set return value , And call null to return , Then directly interrupt the method
return;
}
}
public void OnActionExecuted(ActionExecutedContext context){
}
}
test 
Two .ActionExecutedContext Use
ActionExecutedContext Corresponding After method execution ,
Sure Get the return value of the execution
but Unable to get parameters of function (ActionExecutedContext No, ActionArguments attribute )
1. Get the return value , Record some data
If there are some record tables that need to be written , If the cache needs to be set , You can use ,
Direct access to Result Attribute is enough
public class TokenFilter : IActionFilter
{
private readonly ILogger<TokenFilter> logger;
public TokenFilter(ILogger<TokenFilter> logger)
{
this.logger = logger;
}
public void OnActionExecuting(ActionExecutingContext context)
{
.....
}
public void OnActionExecuted(ActionExecutedContext context)
{
ObjectResult res = (ObjectResult)context.Result;
logger.LogInformation(" The return value of the record method is "+res.Value.ToString());
}
}
Calling method
[HttpGet]
public string ActionFilterTestOne(string paramOne,string paramTwo,string paramThree)
{
logger.LogInformation("The Action is Executing Now");
return "ActionFilterTestOne";
}

defects :
1. No surround AOP Methods , You can only simply add operations before and after , Before and after operation cannot be continuous
(PS: If you want to use surround AOP, Need to use IAsyncActionFilter)
2. Inherit ActionFilterAttribute
Tips :
(PS:ActionFilterAttribute There is a class with the same name , Cannot be in ASP.NET CORE Use in
Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute( correct )
System.Web.Http.Filters.ActionFilterAttribute( error ))
Implementation method provided
ActionFilterAttribute Provides annotation mode configuration Filter,
You can set on classes and methods ,
It realizes all of Filter Related interfaces , Yes 6 Two methods are provided for use
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
//ActionFilterAttribute Implemented multiple interfaces , Can finish
public abstract class ActionFilterAttribute : Attribute, IActionFilter, IFilterMetadata, IAsyncActionFilter, IAsyncResultFilter, IOrderedFilter, IResultFilter
{
protected ActionFilterAttribute();
public int Order {
get; set; }
// Call before method
public virtual void OnActionExecuted(ActionExecutedContext context);
// After the method is called
public virtual void OnActionExecuting(ActionExecutingContext context);
// Method surround call
[DebuggerStepThrough]
public virtual Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next);
// Here is the result Filter
public virtual void OnResultExecuted(ResultExecutedContext context);
public virtual void OnResultExecuting(ResultExecutingContext context);
[DebuggerStepThrough]
public virtual Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next);
}
example :
/// <summary>
/// Filter annotation
/// </summary>
public class TestAttributeFilter : ActionFilterAttribute
{
// When using ActionFilterAttribute As an annotation , You cannot log it , This is a little inconvenient
// But it did ActionFilterAttribute The class of can also be registered as one and the above IActionFilter The same serious
//Filter( As an annotation, you don't have to StartUp register )
public override void OnActionExecuted(ActionExecutedContext context)
{
FileInfo file = new FileInfo(@$"C:\Users\F1338705\source\repos\ActionFilterLearning\ActionFilterLearning\wdnmd.txt");
StreamWriter streamWriter = file.AppendText();
streamWriter.WriteLine(" Use Attribute After the implementation of the method :After");
streamWriter.Close();
base.OnActionExecuted(context);
}
public override void OnActionExecuting(ActionExecutingContext context)
{
FileInfo file = new FileInfo(@$"C:\Users\F1338705\source\repos\ActionFilterLearning\ActionFilterLearning\wdnmd.txt");
StreamWriter streamWriter = file.AppendText();
streamWriter.WriteLine(" Use Attribute Before the execution of the method :Before");
streamWriter.Close();
base.OnActionExecuting(context);
}
}
[HttpGet]
[TestAttributeFilter]
public string ActionFilterTestOne(string paramOne,string paramTwo,string paramThree)
{
logger.LogInformation("The Action is Executing Now");
return "ActionFilterTestOne";
}
view log file 
3. around AOP Of IAsyncActionFilter Asynchronous filter
ASP.NET CORE Use
IAsyncActionFilter To complete the surrounding AOP
It can be executed in two ways
1. Synchronization mode
example :
public class RoundFilter : IAsyncActionFilter
{
private readonly ILogger<RoundFilter> logger;
public RoundFilter(ILogger<RoundFilter> logger)
{
this.logger = logger;
}
// If you don't add async Keywords are still running synchronously
// Methods with ActionExcutingContext Parameters , You can also next Of Invoke Method to get
//ActionExecutedContext To get the return value
// Because it is a synchronous method , You have to go back to one Task, If you choose to add async There is no need to return Task
public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
logger.LogInformation(" around ------------ Before method execution ");
// If you don't call next Method , Will not execute the cut in method
next.Invoke();
// It is recommended that Action As a method, it returns directly after execution ,
Action action = () => {
logger.LogInformation(" around ---------- After method execution "); };
return Task.Run(action);
}
}
To configure :
services.AddMvc(option => {
option.Filters.Add(typeof(RoundFilter));// Also press the normal configuration
});
Interface :
[HttpGet]
//[TestAttributeFilter]
public string ActionFilterTestOne(string paramOne,string paramTwo,string paramThree)
{
logger.LogInformation("The Action is Executing Now");
return "ActionFilterTestOne";
}

2. Asynchronous way
The asynchronous way is simpler
example :
public class RoundFilter : IAsyncActionFilter
{
private readonly ILogger<RoundFilter> logger;
public RoundFilter(ILogger<RoundFilter> logger)
{
this.logger = logger;
}
//
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
logger.LogInformation(" Get parameters before wrapping method execution ");
IDictionary<string, object> ArgsMap = context.ActionArguments;
foreach (KeyValuePair<string, object> pair in ArgsMap)
logger.LogInformation(" The parameter name is " + pair.Key + " | Parameter values for " + pair.Value);
// Can run next Method to get the ActionExecutedContext object , So as to obtain the return value and other information
ActionExecutedContext actionExecutedContext = await next();
ObjectResult result = (ObjectResult)actionExecutedContext.Result;
logger.LogInformation(" The return value of the method after execution is " + result.Value.ToString());
}
}

You can like it at the end .
边栏推荐
- VM virtual machine has no un bridged host network adapter, unable to restore the default configuration
- (translation) timing of website flow chart and user flow chart
- How to write abstract in English thesis?
- RTSP/Onvif协议视频平台EasyNVR服务一键升级功能的使用教程
- How mantium uses deepspeed to implement low latency gpt-j reasoning on Amazon sagemaker
- Solution: runtimeerror: expected object of scalar type int but got scalar type double
- Life related - ten years of career experience (turn)
- SwiftUI一日速成
- Method of test case design -- move combination, causal judgment
- APISIX 在 API 和微服务领域的探索
猜你喜欢

How mantium uses deepspeed to implement low latency gpt-j reasoning on Amazon sagemaker

2021 CIKM |GF-VAE: A Flow-based Variational Autoencoder for Molecule Generation
![Acwing game 61 [End]](/img/e3/191f7d888fc8cced608d41ef837a92.png)
Acwing game 61 [End]

生活相关——十年的职业历程(转)

1. Mx6u system migration-6-uboot graphical configuration

吴恩达机器学习课后习题——逻辑回归

VM virtual machine has no un bridged host network adapter, unable to restore the default configuration

构建关系抽取的动词源

Tutorial on using the one click upgrade function of the rtsp/onvif protocol video platform easynvr service

makefile知识再整理(超详细)
随机推荐
吴恩达机器学习课后习题——线性回归
[project chapter - how to write and map the business model? (3000 word graphic summary suggestions)] project plan of innovation and entrepreneurship competition and application form of national Entrep
Apisex's exploration in the field of API and microservices
远坂凛壁纸
荐书|《DBT技巧训练手册》:宝贝,你就是你活着的原因
How to write the abbreviation of the thesis?
This article takes you to graph transformers
Comprehensive evaluation and decision-making method
I.MX6U-ALPHA开发板(主频和时钟配置实验)
Solution: runtimeerror: expected object of scalar type int but got scalar type double
Leetcode:1184. Distance between bus stops -- simple
Dynamic planning for stair climbing
What model is good for the analysis of influencing factors?
建设面向青少年的创客教育实验室
What format should be adopted when the references are foreign documents?
1. Mx6u-alpha development board (main frequency and clock configuration experiment)
[binary tree] the longest interleaved path in a binary tree
Linear basis property function code to achieve 3000 words detailed explanation, with examples
`Oi problem solving ` ` leetcode '2040. The k-th minor product of two ordered arrays
Can literature | relationship research draw causal conclusions