返回自定义错误WebApi ASP.NET 5 HttpResponseException错误状态代码

时间:2016-05-12 10:11:38

标签: c# asp.net angularjs asp.net-web-api asp.net5

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 });

1 个答案:

答案 0 :(得分:0)

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

相关问题