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:
- It can't handle json message as above example shows a 502 bad gateway error.
- For a basic string, it works but my text is in description, and the body is still "bad request".
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?