【问题标题】:Return custom errors WebApi ASP.NET 5 HttpResponseException wrong status code返回自定义错误 WebApi ASP.NET 5 HttpResponseException 错误状态码
【发布时间】: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


    【解决方案1】:

    为了回答您更新的问题,他们删除了对 HttpResponseException 的使用,因为它鼓励了使用异常进行流控制的不良做法。见https://github.com/aspnet/Mvc/issues/4311

    【讨论】:

    • 谢谢,这就解释了。文档严重缺乏
    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多