.net webapi 过滤器使用(异常日志)

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

常用的过滤器有三种:OnAuthorization、ActionFilterAttribute、ExceptionFilterAttribute本文件主要记录使用ExceptionFilterAttribute记录接口的异常日志,包括请求参数、响应结果,耗时等

常用的过滤器有三种:OnAuthorization、ActionFilterAttribute、ExceptionFilterAttribute

本文件主要记录使用ExceptionFilterAttribute记录接口的异常日志,包括请求参数、响应结果,耗时等

直接上代码:

.net webapi 过滤器使用(异常日志).net webapi 过滤器使用(异常日志)

 1 using Newtonsoft.Json;  2 using ServiceRef;  3 using System;  4 using System.Collections.Generic;  5 using System.IO;  6 using System.Linq;  7 using System.Net;  8 using System.Net.Http;  9 using System.Net.Http.Headers; 10 using System.Text; 11 using System.Threading; 12 using System.Threading.Tasks; 13 using System.Web.Http; 14 using System.Web.Http.ExceptionHandling; 15 using System.Web.Http.Filters; 16  17 namespace WebApi.App_Start 18 { 19     /// <summary> 20     /// 异常过滤器 21     /// </summary> 22     public class ExceptionFilter : ExceptionFilterAttribute 23     {        24  25         ///// <summary> 26         ///// 异步写异常 27         ///// </summary> 28         ///// <param name="actionExecutedContext"></param> 29         ///// <param name="cancellationToken"></param> 30         //public override async Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 31         //{ 32         //    //1.获取异常信息 33         //    string errorMsg = actionExecutedContext.Exception.ToString(); 34  35         //    //2.对获取的异常信息进行处理 36         //    using (StreamWriter writer = File.AppendText("d:/err.txt")) 37         //    { 38         //        await writer.WriteLineAsync(errorMsg); 39         //    } 40         //} 41  42         public override void OnException(HttpActionExecutedContext actionExcutedContext) 43         { 44             HttpRequestMessage request = actionExcutedContext.Request; 45             string controllerName = actionExcutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName; 46             string actionName = actionExcutedContext.ActionContext.ActionDescriptor.ActionName; 47             string content = request.Content.ReadAsStringAsync().Result; 48             string headers = GetCollections(request.Headers); 49             string exceptionMessage = actionExcutedContext.Exception.Message; 50             string exceptionTrace = actionExcutedContext.Exception.StackTrace; 51             string arguments = JsonConvert.SerializeObject(actionExcutedContext.ActionContext.ActionArguments); 52             string url = request.RequestUri.AbsoluteUri; 53             StringBuilder sb = new StringBuilder(); 54             sb.AppendFormat("URL:{0}rn", url); 55             sb.AppendFormat("Controller:{0}rn", controllerName); 56             sb.AppendFormat("Action:{0}rn", actionName); 57             sb.AppendFormat("Arguments:{0}rn", arguments); 58             sb.AppendFormat("Content:{0}rn", content); 59             sb.AppendFormat("Headers:{0}rn", headers); 60             sb.AppendFormat("ExceptionMessage:{0}rn", exceptionMessage); 61             sb.AppendFormat("ExceptionTrace:{0}rn", exceptionTrace); 62             actionExcutedContext.Response = new HttpResponseMessage() { Content = new StringContent(sb.ToString()), StatusCode = System.Net.HttpStatusCode.InternalServerError }; 63             //记录日志 64  65             string errMsg = ""; 66             sb.Clear(); 67             sb = null; 68             base.OnException(actionExcutedContext); 69         } 70         /// <summary> 71         /// 获取Action 参数 72         /// </summary> 73         /// <param name="Collections"></param> 74         /// <returns></returns> 75         public string GetCollections(HttpRequestHeaders Collections) 76         { 77             string Parameters = string.Empty; 78             if (Collections == null || Collections.Count() == 0) 79             { 80                 return Parameters; 81             } 82             foreach (var coll in Collections) 83             { 84                 if (coll.Value.Count() > 0) 85                 { 86                     Parameters += string.Format("{0}={1}&", coll.Key, coll.Value.FirstOrDefault().ToString()); 87                 } 88             } 89             if (!string.IsNullOrWhiteSpace(Parameters) && Parameters.EndsWith("&")) 90             { 91                 Parameters = Parameters.Substring(0, Parameters.Length - 1); 92             } 93             return Parameters; 94         } 95     } 96 }

View Code