2012-10-22 93 views
8

是否有改變的錯誤信息,如網絡API的默認行爲的一種方式:asp.net的Web API - 默認錯誤消息

GET /trips/abc 

會迴應(轉述):

HTTP 500 Bad Request 

{ 
    "Message": "The request is invalid.", 
    "MessageDetail": "The parameters dictionary contains a null entry for parameter 'tripId' of non-nullable type 'System.Guid' for method 'System.Net.Http.HttpResponseMessage GetTrip(System.Guid)' in 'Controllers.TripController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter." 
} 

我我想避免發佈關於我的代碼的這個相當詳細的信息,取而代之的是類似於:

HTTP 500 Bad Request 
{ 
    error: true, 
    error_message: "invalid parameter" 
} 

我可以在UserController中執行此操作,但代碼執行甚至沒有達到那麼遠。

編輯:

我發現從輸出除去詳細的錯誤消息的一種方式,使用這行代碼在Global.asax.cs中:

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = 
IncludeErrorDetailPolicy.LocalOnly; 

這產生類似這樣的消息:

{ 
    "Message": "The request is invalid." 
} 

這是更好的,但是不正是我想要的 - 我們已經指定了一些數字錯誤代碼,它映射到詳細的錯誤信息的客戶端。我想只輸出相應的錯誤代碼(即我能之前輸出選擇,preferrably通過看發生什麼樣的例外),例如:

{ error: true, error_code: 51 } 

回答

7

你可能想保留的形狀即使您想隱藏有關實際異常的詳細信息,也會將該數據視爲類型HttpError。要做到這一點,你可以添加一個自定義的DelegatingHandler來修改你的服務拋出的HttpError。

這裏的DelegatingHandler如何可能看起來像一個示例:

public class CustomModifyingErrorMessageDelegatingHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) => 
     { 
      HttpResponseMessage response = responseToCompleteTask.Result; 

      HttpError error = null; 
      if (response.TryGetContentValue<HttpError>(out error)) 
      { 
       error.Message = "Your Customized Error Message"; 
       // etc... 
      } 

      return response; 
     }); 
    } 
} 
+0

完美,謝謝! – doque

+3

如果你想知道在哪裏添加它,可以通過調用'config.MessageHandlers.Add(new YourDelegatingHandler())'來添加它,通常在啓動邏輯的'Register(HttpConfiguration config)'方法中。 –

+0

不應該在構建響應內容之後替換響應內容,我們是不是應該首先定製負責構建響應的類/服務? – dgaspar

2

張曼玉的回答爲我工作爲好。感謝發佈!

只是想一些比特她代碼進一步澄清:

HttpResponseMessage response = responseToCompleteTask.Result; 
HttpError error = null; 

if ((!response.IsSuccessStatusCode) && (response.TryGetContentValue(out error))) 
{ 
    // Build new custom from underlying HttpError object. 
    var errorResp = new MyErrorResponse(); 

    // Replace outgoing response's content with our custom response 
    // while keeping the requested MediaType [formatter]. 
    var content = (ObjectContent)response.Content; 
    response.Content = new ObjectContent(typeof (MyErrorResponse), errorResp, content.Formatter); 
} 

return response; 

其中:

public class MyErrorResponse 
    { 
     public MyErrorResponse() 
     { 
      Error = true; 
      Code = 0; 
     } 

     public bool Error { get; set; } 
     public int Code { get; set; } 
    }