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);
    }
  • 相关阅读:
    Ubuntu14.04LTS系统QQ的安装:pidgin-lwqq
    Ubuntu14.04LTS系统输入法的安装
    Linux系统安装及初始化(ubuntu14.04)
    创建RAID并永久挂载RAID
    磁盘管理和磁盘配额
    用户账号组账号概述
    安装及管理程序
    目录和文件管理
    Vi编辑器的工作模式
    Linux命令及使用方法
  • 原文地址:https://www.cnblogs.com/wangx036/p/12786555.html
Copyright © 2011-2022 走看看