是否有改變的錯誤信息,如網絡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 }
完美,謝謝! – doque
如果你想知道在哪裏添加它,可以通過調用'config.MessageHandlers.Add(new YourDelegatingHandler())'來添加它,通常在啓動邏輯的'Register(HttpConfiguration config)'方法中。 –
不應該在構建響應內容之後替換響應內容,我們是不是應該首先定製負責構建響應的類/服務? – dgaspar