![](/img/trans.png)
[英]How to return correct status code when enumeration of IEnumerable fails. ASP.NET WebApi
[英]Return custom errors WebApi ASP.NET 5 HttpResponseException wrong status code
WebAPI / REST允許您發送自定義錯誤消息以及標准狀態代碼,即標題/正文中的402 - 未找到+您自己的消息。
這在ASP.NET 4.X上很有用,但是對於ASP.NET 5 RC 1,有一些不妥之處。
雖然我拋出自定義錯誤的代碼看起來像這樣:
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Ambiguous)
{
Content = feedback, ReasonPhrase = reason }
);
返回的代碼(到Angular)不是指定的代碼(示例中為300)。 在localhost / IIS Express上我得到500 Internal Server Error
,在Azure上生產我得到404 Not Found
。
查看ASP.NET文檔,我看到了可能相關的內容:
如果服務器在發送標頭之前捕獲到異常,它將發送500內部服務器錯誤響應而沒有正文。
https://docs.asp.net/en/latest/fundamentals/error-handling.html#server-exception-handling
那么有沒有人從ASP.NET 5 RC 1 WebAPI向客戶端成功返回帶有自定義(正文)消息的狀態代碼?
更新:
這種方法似乎工作得更好 - 但這並不能解釋為什么HttpResponseException
不起作用。
this.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.HttpBadRequest(new { ex.Message });
為了回答您更新的問題,他們刪除了HttpResponseException的使用,因為它鼓勵了使用異常進行流量控制的不良做法。 請參閱https://github.com/aspnet/Mvc/issues/4311 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.