web API 的异常处理

 

实现自定义的异常处理类

---------------------------------------------------------------------

public class MyExceptionFilter : IExceptionFilter
{
  public bool AllowMultiple => true;

  public async Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
  {
    // throw new NotImplementedException();
    Exception ex= actionExecutedContext.Exception;
    //Console.WriteLine(ex.ToString());
  }
}

 

 

注册自定义异常处理类

----------------------------------------------------------------------------

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 MyFilter());
    config.Filters.Add(new MyExceptionFilter());
  }
}

posted @ 2020-11-24 20:18  MaxBruce  阅读(80)  评论(0编辑  收藏  举报