C#MVC中的Filter过滤器使用

Filter作为.NET中的过滤器,可以捕捉异常,通常情况下是封装起来使用的:

public class ExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(ExceptionFilter));
        public Task OnExceptionAsync(ExceptionContext context)
        {
            var rq = context.HttpContext.Request;
            var response = context.HttpContext.Response;
            bool isAjax = false;
            var ex = context.Exception;

            var xreq = rq.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                isAjax = rq.Headers["x-requested-with"] == "XMLHttpRequest";
            }

            if (context.ExceptionHandled == false)
            {
                string msg = "";
#if DEBUG
                msg = JsonHelper.SerializeCamel(
                       new { new RongboSystemException().Code, ex.Message }); ;
#endif
                StringBuilder sb = new StringBuilder();
                sb.Append(Environment.NewLine + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sb.Append(Environment.NewLine + "====异常信息====");
                sb.Append(Environment.NewLine + "异常抛出源:" + ex.Source);
                sb.Append(Environment.NewLine + "异常方法:" + ex.TargetSite);
                sb.Append(Environment.NewLine + "异常信息:" + ex.Message);
                sb.Append(Environment.NewLine + "堆栈信息:" + ex.StackTrace);
                sb.Append(Environment.NewLine + "--------------------------------------------------------------------------------------------------");
                logger.Error($"出现未处理异常【MvcApplication】:{sb.ToString()}");

                if (isAjax)
                {
                    //用户输入参数异常返回格式
                    if (ex is RongboArgumentException)
                    {
                        var rongboArgumentException = ex as RongboArgumentException;

                        msg = JsonHelper.SerializeCamel(
                        new { rongboArgumentException.Code, rongboArgumentException.Message, rongboArgumentException.Data });
                    }

                    if (ex is RongboBaseException)
                    {
                        var rongboBaseException = ex as RongboBaseException;

                        msg = JsonHelper.SerializeCamel(
                       new { rongboBaseException.Code, rongboBaseException.Message, rongboBaseException.Data });
                    }
                }
                context.Result = new ContentResult
                {
                    Content = msg,
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "application/json;charset=utf-8"
                };

            }
            context.ExceptionHandled = true; //异常已处理了

            return Task.CompletedTask;
        }
    }

封装完成后,在Startup中调用:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //JSON编码
            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });
            services.AddControllers(options => options.Filters.Add(new ExceptionFilter()));
       }

你可能感兴趣的:(.NET,Core,MVC,c#,mvc)