.net core 攔截器和全局異常捕獲


1.編寫全局異常攔截類
public class MyExpextFilter : ExceptionFilterAttribute
    {
        private ILogger<MyExpextFilter> logger;
        public MyExpextFilter(ILogger<MyExpextFilter> logger)
        {
            this.logger = logger;
        }
        public override void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled) //如果錯誤沒有處理過
            {
                if (this.IsAjax(context.HttpContext.Request))
                {
                    context.Result = new JsonResult(new VReturnMessage<object> //
                    {
                        Message = context.Exception.Message,
                        ReturnCode = context.HttpContext.Response.StatusCode,
                        Data = new List<object>()
                    });
                }
                logger.LogError(context.Exception.Message);
                context.ExceptionHandled = true; //表示錯誤已經處理過
            }
        }
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            this.OnException(context);
            return Task.CompletedTask;
        }
        //header中 x-requested-with  XMLHttpRequest  //表明是AJax異步
        private bool IsAjax (HttpRequest httpRequest)
        {
            string requestType = httpRequest.Headers["x-requested-with"];
            return "XMLHttpRequest".Equals(requestType, StringComparison.Ordinal);
        }
    }
2. 注冊攔截器
2.1 ServiceFilter 注冊
在需要攔截的地方增加特性 [ServiceFilter(typeof(MyExpextFilter))] 並在ConfigureServices 中注冊MyExpextFilter   ->  services.AddScoped(typeof(MyExpextFilter));
2.2 TypeFilter 注冊
在需要攔截的地方增加特性 [TypeFilter(typeof(MyExpextFilter))] 此方式不需要在ConfigureServices 中注冊
2.3 FilterFactory 注冊
編寫攔截Factory 類
    public class ExpertFilterFactory : Attribute,IFilterFactory
    {
        public bool IsReusable => true;
        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            return serviceProvider.GetService(typeof(MyExpextFilter)) as IFilterMetadata;
        }
    }
在需要攔截的地方增加特性 [ExpertFilterFactory] 並在ConfigureServices 中注冊MyExpextFilter   ->  services.AddScoped(typeof(MyExpextFilter));
2.4 全局注冊
services.AddControllersWithViews(opetation =>
{
  opetation.Filters.Add<MyExpextFilter>();
 });
3. Filter攔截順序
用order參數 從小到大開始
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM