iT邦幫忙

1

.Net Core OnActionExecutionAsync

  • 分享至 

  • xImage
  •  

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

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-7.0#implementation


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言