【问题标题】:How to send custom http 400 error message with mvc controller?如何使用 mvc 控制器发送自定义 http 400 错误消息?
【发布时间】:2020-09-23 04:26:03
【问题描述】:

很奇怪,不知道为什么。 我有一个旧的 mvc 站点,想添加一些自定义错误消息。比如http状态码是400,我想输出

{
    "error": {
        "code": "",
        "message": "xxx is wrong with ..."
    }
}

所以我使用了here的解决方案,

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, @"{
                ""error"": {
                    ""code"": "",
                    ""message"": ""xxx is wrong with ...""
                }
            }");

但是有两个问题:

  1. 无法处理 json 消息,因为上面的示例显示 502 bad gateway 错误。
  2. 对于基本字符串,它可以工作,但我的文本在描述中,并且正文仍然是“错误请求”。

我尝试了很多其他方法(例如发送HttpResponseMessage),但都没有奏效。使用 HttpResponseMessage,

return new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                ReasonPhrase = HttpStatusCode.BadRequest.ToString(),
                Content = new StringContent("hello")
            };

我实际上得到了 status 200 并且正文是:

StatusCode: 400, ReasonPhrase: 'BadRequest', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}

所以我想输出带有一些 Json 正文的 BadRequest 状态消息,我该怎么做?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    两天后,我终于解决了。

    上一个 stackoverflow 问题的解决方案实际上可以在我的本地机器上运行,但是当我部署到服务器时没有输出任何内容。

    在我的本地机器上,VS 将在 IIS express 中运行代码,而在服务器上它是 IIS。所以在 web.config 中,我实际上需要这些行:

    <system.webserver>
        <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough"></httpErrors>
    </system.webserver>
    

    【讨论】:

      猜你喜欢
      • 2016-01-27
      • 2019-10-19
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 2011-12-29
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多