如果在 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 servicesconfig.Filters.Add(new ExceptionHandlingAttribute());// Web API routesconfig.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,如需轉載請自行聯系原作者
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态