【发布时间】:2016-09-08 02:30:13
【问题描述】:
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 });
【问题讨论】:
标签: c# asp.net angularjs asp.net-web-api asp.net5