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()));
       }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值