0

Quite strange and not sure why. I have an old mvc site and wants to add some custom error message. For example, when http status code is 400, I want to output

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

So I used the solution here,

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

but there are two problems:

  1. It can't handle json message as above example shows a 502 bad gateway error.
  2. For a basic string, it works but my text is in description, and the body is still "bad request". enter image description here

I tried lots of other ways (e.g. send out HttpResponseMessage), but none worked. With HttpResponseMessage,

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

I actually got status 200 and body is:

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

So I want to output a BadRequest status message with some Json body, how can I do that?

daxu
  • 3,514
  • 5
  • 38
  • 76

1 Answers1

0

After two days, I finally worked it out.

The solution from previous stackoverflow question actually works on my local machine, but doesn't output anything when I deployed to a server.

On my local machine, VS will run code in IIS express, and on the server it is IIS. So in the web.config, I actually need these lines:

<system.webserver>
    <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough"></httpErrors>
</system.webserver>
daxu
  • 3,514
  • 5
  • 38
  • 76