2015-11-14 39 views
0

序言:此問題與"Exception Handling in ASP.net Web API"不同,因爲OP正在尋找自定義錯誤處理,而不是全局處理。它也不同於以前回答的其他早期問題,因爲那些早期版本的Web API不是版本2.還要注意我將自己回答這個問題。花了很長時間才找到正確的答案。ASP.NET Web API中的全局錯誤處理2

問題是:我如何全局處理Web API 2.0中的錯誤?我爲MVC設置的錯誤處理沒有爲web api調用激活,我需要一般處理任何拋出的錯誤,以便將相關的錯誤信息返回給客戶端。

回答

1

this asp.net article中正確回答了全局錯誤處理。然而,這些文章缺少一些重要的觀點來讓代碼真正起作用。

本文涵蓋的細節,但在這裏它是在一個概括地說:

  1. 處理已經包含在System.Web.Http.ExceptionHandling文章中的類是已經在這個庫中,所以沒有必要全局誤差重寫它們。

  2. 您需要編寫的唯一類是爲您的應用程序定製的類。在文章中,他們將其稱爲「OopsExceptionHandler」。但是,文章中編寫的那個不會編譯。這是更新的代碼,做工作:

    public class OopsExceptionHandler : ExceptionHandler 
    { 
        public override void Handle(ExceptionHandlerContext context) 
        { 
        context.Result = new TextPlainErrorResult 
        { 
         //If you want to return the actual error message 
         //Content = context.Exception.Message 
         Request = context.ExceptionContext.Request, 
         Content = "Oops! Sorry! Something went wrong." + 
            "Please contact [email protected] so we can try to fix it." 
        }; 
    } 
    
    private class TextPlainErrorResult : IHttpActionResult 
    { 
        public HttpRequestMessage Request { get; set; } 
    
        public string Content { get; set; } 
    
        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
        { 
         HttpResponseMessage response = 
             new HttpResponseMessage(HttpStatusCode.InternalServerError); 
         response.Content = new StringContent(Content); 
         response.RequestMessage = Request; 
         return Task.FromResult(response); 
        } 
    } 
    } 
    
  3. 然後,您需要註冊的ExceptionHandler。這樣的例子並不在文章中給出的,所以在這裏它是:

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

這行雲在WebApiConfig文件,寄存器方法。請注意,它使用'替換'而不是'添加',因爲它會在添加時出錯。框架只允許有一個。

這就是所有需要的。要測試,請從您的Web API中引發錯誤,您將看到作爲webAPI調用內容返回的錯誤消息。請注意,將錯誤消息返回給客戶端存在安全隱患,因此請確保這是您真正想要的。