webapi使用ExceptionFilterAttribute过滤器
2021-01-23 00:12
标签:str public res abs 文章 sys format server webapi 文章 webapi使用ExceptionFilterAttribute过滤器 标签:str public res abs 文章 sys format server webapi 原文地址:https://www.cnblogs.com/fanfan-90/p/12075592.htmlpublic class ApiExceptionFilterAttribute:ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExcutedContext)
{
HttpRequestMessage request = actionExcutedContext.Request;
string controllerName = actionExcutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
string actionName = actionExcutedContext.ActionContext.ActionDescriptor.ActionName;
string content = request.Content.ReadAsStringAsync().Result;
string exceptionMessage = actionExcutedContext.Exception.Message;
string exceptionTrace = actionExcutedContext.Exception.StackTrace;
string arguments = JsonConvert.SerializeObject(actionExcutedContext.ActionContext.ActionArguments);
string url = request.RequestUri.AbsoluteUri;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("URL:{0}
", url);
sb.AppendFormat("Controller:{0}
", controllerName);
sb.AppendFormat("Action:{0}
",actionName);
sb.AppendFormat("Arguments:{0}
",arguments);
sb.AppendFormat("Content:{0}
",content);
sb.AppendFormat("ExceptionMessage:{0}
", exceptionMessage);
sb.AppendFormat("ExceptionTrace:{0}
", exceptionTrace);
actionExcutedContext.Response = new HttpResponseMessage() { Content = new StringContent(sb.ToString()),StatusCode=System.Net.HttpStatusCode.InternalServerError };
//记录日志
sb.Clear();
sb = null;
base.OnException(actionExcutedContext);
}
}
文章标题:webapi使用ExceptionFilterAttribute过滤器
文章链接:http://soscw.com/index.php/essay/45651.html