2017-05-05 46 views
0

我uising網頁API 2,爲客戶開發服務,管理我們使用的是ExceptionsFilterAttribute錯誤,但你也知道,在這個級別不是所有的異常被捕獲。 一些錯誤募集protected void Application_AuthenticateRequest(Object sender, EventArgs e),我想處理,並將處理髮送自定義消息,我們的客戶給他更多的細節有關的錯誤,要解決這個我創建了一個GlobalExceptionHandler的WebAPI 2全局異常處理不會引發

public class GlobalExceptionHandler: ExceptionHandler 
{ 
//A basic DTO to return back to the caller with data about the error 
private class ErrorInformation 
{ 
public string Message { get; set; } 
public DateTime ErrorDate { get; set; } 
} 

public override void Handle(ExceptionHandlerContext context) 
{ 

//Return a DTO representing what happened 
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, 
new ErrorInformation { Message="We apologize but an unexpected error occured. Please try again later.", ErrorDate=DateTime.UtcNow })); 

//This is commented out, but could also serve the purpose if you wanted to only return some text directly, rather than JSON that the front end will bind to. 
//context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, "We apologize but an unexpected error occured. Please try again later.")); 
} 
} 

在WebApiConfig我加入這行:

config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); 

的的Application_AuthenticateRequest提出了一些錯誤,但從未達到GlobalExceptionHandler

你有什麼想法我該如何解決這個問題?

在此先感謝。

回答

1

Application_AuthenticateRequest不在Web API管道中。所以,如果一個例外是在這個方法中那些可以由Web API異常處理程序捕獲拋出,因爲Web API管線開始之前拋出異常。

有兩種方法可以做到這一點:

  1. 要麼改變身份驗證機制,利用Web API認證(IAuthenticationFilter),而不是Application_AuthenticateRequest。

    • 如果這個項目只有Web API相關的控制器,不像MVC和所有。
  2. 或者使用的Application_Error在Global.asax.cs中文件趕上Application_AuthenticateRequest

+0

我用IAuthenticationFilter爲我工作得很好拋出的異常 –