title: How to send custom http 400 error message with mvc controller?
body: <p>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</p>
  <pre><code>{
      &quot;error&quot;: {
          &quot;code&quot;: &quot;&quot;,
          &quot;message&quot;: &quot;xxx is wrong with ...&quot;
      }
  }
  </code></pre>
  <p>So I used the solution <a href="https://stackoverflow.com/questions/31287090/mvc-controller-return-a-bad-request">here</a>,</p>
  <pre><code>return new HttpStatusCodeResult(HttpStatusCode.BadRequest, @&quot;{
                  &quot;&quot;error&quot;&quot;: {
                      &quot;&quot;code&quot;&quot;: &quot;&quot;,
                      &quot;&quot;message&quot;&quot;: &quot;&quot;xxx is wrong with ...&quot;&quot;
                  }
              }&quot;);
  </code></pre>
  <p>but there are two problems:</p>
  <ol>
  <li>It can't handle json message as above example shows a 502 bad gateway error.</li>
  <li>For a basic string, it works but my text is in description, and the body is still &quot;bad request&quot;.
  <a href="https://i.stack.imgur.com/D81fT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D81fT.png" alt="enter image description here" /></a></li>
  </ol>
  <p>I tried lots of other ways (e.g. send out <code>HttpResponseMessage</code>), but none worked. With HttpResponseMessage,</p>
  <pre><code>return new HttpResponseMessage(HttpStatusCode.BadRequest)
              {
                  ReasonPhrase = HttpStatusCode.BadRequest.ToString(),
                  Content = new StringContent(&quot;hello&quot;)
              };
  </code></pre>
  <p>I actually got <strong><code>status 200</code></strong> and body is:</p>
  <pre><code>StatusCode: 400, ReasonPhrase: 'BadRequest', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
  {
  Content-Type: text/plain; charset=utf-8
  }
  </code></pre>
  <p>So I want to output a BadRequest status message with some Json body, how can I do that?</p>