gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:49:36 25 4
gpt4 key购买 nike

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 文档,我看到了一些可能相关的内容:

If the server catches an exception before the headers have been sent it will send a 500 Internal Server Error response with no body.

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 .

关于c# - 返回自定义错误 WebApi ASP.NET 5 HttpResponseException 错误状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com