zoukankan      html  css  js  c++  java
  • .net mvc 异常处理 IExceptionFilter,保存请求参数

    1. 异常处理代码

    /// <summary>
    /// 异常处理
    /// </summary>
    public class WebExceptionFilterAttribute : IExceptionFilter
    {
        public virtual void OnException(ExceptionContext context)
        {
            var url = context.HttpContext.Request.Url?.AbsoluteUri;
            if (string.IsNullOrEmpty(url))
            {
                string action = context.RouteData.Values["action"].ToString();
                string controller = context.RouteData.Values["controller"].ToString();
                string queryParam = context.HttpContext.Request.QueryString.ToString();
                url = $"{controller}/{action}?{queryParam}";
            }
    
            // 获取body参数
            int dataLength = Convert.ToInt32(context.HttpContext.Request.InputStream.Length);
            byte[] bytes = new byte[dataLength];
            context.HttpContext.Request.InputStream.Position = 0; //读过一次后位置需要修改回0
            context.HttpContext.Request.InputStream.Read(bytes, 0, dataLength);
            var bodyParam = Encoding.UTF8.GetString(bytes);
    
            // 传入日志方法
            LogHelper.Write(Level.Error,url,context.Exception, OperatorProvider.Instance?.Current?.LoginName, bodyParam);
    
            var result = new AjaxResult(ResultType.Success, "系统异常", context.Exception.Message);
            context.Result = new ContentResult {Content = result.ToJson()};
            // 标记异常已处理
            context.ExceptionHandled = true;
        }
    }

    2. 添加到 FilterConfig 

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new WebExceptionFilterAttribute());
        }
    }

    3. Global 注册

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
  • 相关阅读:
    jstack 分析程序性能
    网关-zuul介绍 第一篇 网关解决的问题
    通过Fegin远程调用 ,返回JPA Page 对象报错
    css自定义字体
    CSS3选择器
    表格操作
    商品筛选条件
    多级菜单
    一排元素往下掉
    控制提示框不溢出父级盒子
  • 原文地址:https://www.cnblogs.com/wangx036/p/12786555.html
Copyright © 2011-2022 走看看