1

How can I return a Json response ALWAYS, it doesn't matter if the HTTP Code needs to be 200, 401, or another one.

For the HTTP 200 the Json is sent with return Ok(response); //where response is a model. For HTTP 401 (Unauthorized) I have the following:

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent(msg),
                    ReasonPhrase = msg
                });

But msg needs to be an String... I cannot make it work with a model to return a JSON.

The same happens with BadRequest or other HTTP status.

Faabass
  • 1,394
  • 8
  • 29
  • 58

1 Answers1

0

No one says that the content of StringContent cannot be a serialized object. Try this:

// uses Newtonsoft.Json
var serializedString = JsonConvert.SerializeObject(yourObject);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
    Content = new StringContent(serializedString, System.Text.Encoding.UTF8, "application/json"),
    ReasonPhrase = msg
});

Credit goes to Put content in HttpResponseMessage object?

Florian Lim
  • 5,332
  • 2
  • 27
  • 28