ASP.NET 通过拦截器记录错误日志

  • A+
所属分类:.NET技术
摘要

    主要是记录一下实现的错误日志拦截,可以在拦截器里面控制返回的信息,把错误信息处理后返回给请求端。


前言

    主要是记录一下实现的错误日志拦截,可以在拦截器里面控制返回的信息,把错误信息处理后返回给请求端。

代码实战

拦截器

    /// <summary>     /// 接口异常捕捉过滤器     /// </summary>     [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]     public class ApiErrorHandleAttribute : ExceptionFilterAttribute     {         public override void OnException(HttpActionExecutedContext actionExecutedContext)         {             base.OnException(actionExecutedContext);             actionExecutedContext.Response = GetResponse(actionExecutedContext);         }          /// <summary>         /// 捕捉异常后响应方法         /// </summary>         private HttpResponseMessage GetResponse(HttpActionExecutedContext actionExecutedContext)         {             var requesthost = actionExecutedContext.ActionContext.Request.RequestUri.ToString();//当前请求的地址,包括ip加接口地址             var method = actionExecutedContext.ActionContext.Request.Method.ToString();//当前请求是POST/GET/PUT/DELETE ……             var controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;//当前请求的控制器所在全路径:xxx.WebAPI.Controllers.xxxController             var action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; //当前请求的方法             var paramters = actionExecutedContext.ActionContext.ActionArguments; //获取当前请求的参数             var ip = HttpContext.Current.Request.UserHostAddress;                         LogHelper.Error($"错误信息:URL:{actionExecutedContext.Request.RequestUri},--参数信息:{paramters.ToJson()},--actionExecutedContext.Exception:{actionExecutedContext.Exception.ToJson()}");             var response = new { code = 506, message = $"{actionExecutedContext.Exception.Message},URL:{actionExecutedContext.Request.RequestUri}", ex = actionExecutedContext.Exception };                         return JsonHelper.ToHttpResponseMessage(response);         }      } 

工具类方法

    public static class JsonHelper     {         /// <summary>         /// 转化为json格式的HttpResponseMessage         /// </summary>         public static HttpResponseMessage ToHttpResponseMessage(object obj)         {             string str;             if (obj is string || obj is char)             {                 str = obj.ToString();             }             else             {                 str = obj.ToJson();             }             var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };             return result;         }          /// <summary>         /// 转化为json字符串,默认的时间格式         /// </summary>         /// <param name="obj">要被转化的对象</param>         /// <returns>json字符串</returns>         public static string ToJson(this object obj)         {             return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" });         }     }