2

I'm working on a web API project that uses the .NET MVC 4 framework. My API is focused around returning JOSN objects, and works perfectly except for when I want to return exceptions in a JSON format.

The code I have below is what I am using to try and force a JSON return, but the response generated from this code is the default HTML content type. I'm looking for a way to return an exception using the "application/json" content type. Any suggestions?

public static void ThrowHttpException(HttpStatusCode code, string content)
{
    string message = JsonConvert.SerializeObject(new { message = content });
    var resp = new HttpResponseMessage(code)
    {
        Content = new StringContent(message),
        ReasonPhrase = null
    };
    throw new HttpResponseException(resp);
}
miken.mkndev
  • 1,821
  • 3
  • 25
  • 39

1 Answers1

1

You should probably create action like this:

public IHttpActionResult ThrowHttpException(HttpStatusCode code, string content)
{
    string message = JsonConvert.SerializeObject(new { message = content });
    var resp = new HttpResponseMessage(code)
    {
        Content = new StringContent(message),
        ReasonPhrase = null
    };
    return resp;
}

Instead of throwin an exception you should return from the action the response object.

mr100
  • 4,340
  • 2
  • 26
  • 38