Skip to content

Instantly share code, notes, and snippets.

@alanwei43
Created July 9, 2018 09:29
Show Gist options
  • Save alanwei43/1617777c1da890b846ee9240e6950826 to your computer and use it in GitHub Desktop.
Save alanwei43/1617777c1da890b846ee9240e6950826 to your computer and use it in GitHub Desktop.
ASP.Net Web API 全局异常捕获
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");
}
}
}
@alanwei43
Copy link
Author

添加全局过滤器:

    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());
        }
    }

@ichengzi
Copy link

ichengzi commented Oct 8, 2018

注:只能用于asp.net web api2 以上的版本

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment