5

I have a function in ApiController, which is supposed to output an object of some kind. That function receives that object in already serialized format. In order for the function to end up returing valid JSON, I need to turn it into JObject, like this:

    [HttpGet]
    public object MyFunction()
    {
        string result = .......;
        return JObject.Parse(result);
    }

Question is: the result is already a valid JSON, and I want to return it as-is, without any more processing. If my class was a regular Controller, I could have just returned a ContentResult, but for some reasons, I cannot turn ApiController into regular Controller in this case.

Any other options?

galets
  • 17,802
  • 19
  • 72
  • 101

1 Answers1

14

If the action returns a System.Net.Http.HttpResponseMessage, ASP.NET Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response.

This option gives you a lot of control over the response message.

Example usage of returning raw json: (Reference https://stackoverflow.com/a/17097919/368552)

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
    return response;
}
Community
  • 1
  • 1
Luke Hutton
  • 10,612
  • 6
  • 33
  • 58
  • I wonder why they didn't just allow us to use ContentResult and Content(myString, "application/json") like in MVC... – MetaGuru Jul 03 '14 at 17:49