Created
July 9, 2018 09:29
-
-
Save alanwei43/1617777c1da890b846ee9240e6950826 to your computer and use it in GitHub Desktop.
ASP.Net Web API 全局异常捕获
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GlobalWebApiExceptionFilter : ExceptionFilterAttribute | |
{ | |
public override void OnException(HttpActionExecutedContext context) | |
{ | |
base.OnException(context); | |
if (context.Exception is NotImplementedException) | |
{ | |
context.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK); | |
context.Response.Content = new System.Net.Http.StringContent("not implement"); | |
} | |
} | |
} |
添加全局过滤器:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new GlobalWebApiExceptionFilter());
}
}
注:只能用于asp.net web api2 以上的版本
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ref: Global Error Handling in ASP.NET Web API 2