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 Internal Server Error 响应。
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 });