.net mvc 异常处理 IExceptionFilter,保存请求参数

2021-03-17 10:27

阅读:452

标签:hand   ajax   provider   ica   oba   rtu   tostring   ebe   reg   

1. 异常处理代码

/// 
/// 异常处理
/// 
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);
}

 

.net mvc 异常处理 IExceptionFilter,保存请求参数

标签:hand   ajax   provider   ica   oba   rtu   tostring   ebe   reg   

原文地址:https://www.cnblogs.com/wangx036/p/12786555.html


评论


亲,登录后才可以留言!