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); }