以往ASP.Net MVC,要在Controller進入Action前、後記錄log或是處理權限判斷,只要override OnActionExecuting及OnActionExecuted即可,如下:
public override void OnActionExecuting(ActionExecutingContext context)
{
//log request data
base.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");
}