以往ASP.Net MVC,要在Controller进入Action前、后记录log或是处理权限判断,只要override OnActionExecuting及OnActionExecuted即可,如下:
public override void OnActionExecuting(ActionExecutingContext context){//log request database.OnActionExecuting(context);}
public override void OnActionExecuted(ActionExecutedContext context){//log resposne data base.OnActionExecuted(context);}
同样方法在.Net Core专案仍可以执行,但.Net Core Method多以非同步方式处理,此时就需使用OnActionExecutionAsync,做法很简单,Action前->await next()->Action后,如下:
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){//get session or check something... //excute async method //before action_logger.WriteLog(Level.Info, _logType, $"before action");await next();//after action _logger.WriteLog(Level.Info, _logType, $"after action");}
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-7.0#implementation