如果在 ASP.NET MVC 应用程序中记录异常信息,我们只需要在 Global.asax 的 Application_Error 中添加代码就可以了,比如:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Error(object sender, EventArgs e)
{
var lastError = Server.GetLastError();
if (lastError != null)
{
Logger.Default.Error("Application_Error", lastError);
Response.StatusCode = 500;
Server.ClearError();
}
}
}
但这一套在 ASP.NET Web API 中并不适用,其解决方式也不是很麻烦,我们先创建 ExceptionHandlingAttribute(继承 ExceptionFilterAttribute):
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var exception = context.Exception;
if (exception != null)
{
Logger.Default.Error("Application_Error", exception);
}
}
}
然后在 WebApiConfig 中注册下:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Filters.Add(new ExceptionHandlingAttribute());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
或者我们在 Action 上面添加 ExceptionHandlingAttribute 属性:
public class ValuesController : ApiController
{
[ExceptionHandlingAttribute]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
如果日志没有记录的话,需要在 Global.asax.cs 中的 Application_Start 添加如下代码:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
....
}
}
本文转自SummerChill博客园博客,原文链接:http://www.cnblogs.com/xishuai/p/asp-net-web-api-global-error-handling.html,如需转载请自行联系原作者