2016-05-16 71 views
2

Stack,Owin WebApi服务忽略ExceptionFilter

由于某些原因,我的Owin WebApi服务忽略了我们的自定义异常处理程序。我正在关注asp.net exception handling的文档。以下是简化的实施细节(清理出商业专有内容)。

你能指出我忽略了什么吗?

自定义异常过滤器:

public class CustomExceptionFilter : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext actionExecutedContext) 
    { 
     actionExecutedContext.Response.StatusCode = HttpStatusCode.NotFound; 
     actionExecutedContext.Response.Content = new StringContent("...my custom business...message...here..."); 
    } 
} 

在启动过程中:

var filter = new CustomExceptionFilter(); 
config.Filters.Add(filter); 
appBuilder.UseWebApi(config); 

测试控制器:

[CustomExceptionFilter] 
public class TestController: ApiController 
{ 
    public void Get() 
    { 
     throw new Exception(); // This is a simplification. 
           // This is really thrown in buried 
           // under layers of implementation details 
           // used by the controller. 
    } 
} 
+0

我有一个项目,做这个确切的模式,除了在OnException修改响应我抛出新的HttpResponseException(new HttpResponseMessage(...'而不是修改'actionExecutedContext'。 –

回答

2

可以TR y执行Global Error Handling in ASP.NET Web API 2。 通过这种方式,您将获得Web API中间件的全局错误处理程序,但不能用于OWIN pippeline中的其他中间件,如授权之一。

如果你想实现一个globlal错误处理中间件,this,thisthis链接可以定位你。

我希望它有帮助。

编辑

关于对@ t0mm13b的评论,我给基于从Khanh TO第一this链路上的一点解释。

对于全局错误处理,您可以编写一个自定义且简单的中间件,只将流程传递到管道中的以下中间件,但在try块内。

如果在管道中的下列中间件中的一个的未处理的异常,将在catch块捕获:

public class GlobalExceptionMiddleware : OwinMiddleware 
{ 
    public GlobalExceptionMiddleware(OwinMiddleware next) : base(next) 
    { } 

    public override async Task Invoke(IOwinContext context) 
    { 
     try 
     { 
      await Next.Invoke(context); 
     } 
     catch (Exception ex) 
     { 
      // your handling logic 
     } 
    } 
} 

Startup.Configuration()方法中,在第一地点添加中间件到管线如果你想处理所有其他中间件的异常。

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     app.Use<GlobalExceptionMiddleware>(); 
     //Register other middlewares 
    } 
} 

如第二this的链接所指向的Tomas Lycken,你可以用这个来处理的Web API中间件产生的异常创建实现IExceptionHandler刚刚抛出捕获的异常,这样的全局异常处理中间件将一类抓住它:

public class PassthroughExceptionHandler : IExceptionHandler 
{ 
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) 
    { 
     // don't just throw the exception; that will ruin the stack trace 
     var info = ExceptionDispatchInfo.Capture(context.Exception); 
     info.Throw(); 
    } 
} 

而且不要忘记在Web API中间件配置过程中更换IExceptionHandler

config.Services.Replace(typeof(IExceptionHandler), new PassthroughExceptionHandler()); 
+0

请在您的回答中简要介绍相关链接的内容。仅仅简单地指向链接#1,链接#2而没有解释是不可原谅的,并且会遭受链接腐烂或者在其他链接中删除答案。 – t0mm13b

+1

@ t0mm13b,我用更完整的解释更新了我的回复。我很抱歉有这么多链接的第一反应。 – jumuro

+0

现在好多了。 – t0mm13b