2016-05-16 114 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