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?

2

1 Answer 1

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;
}
1
  • I wonder why they didn't just allow us to use ContentResult and Content(myString, "application/json") like in MVC...
    – MetaGuru
    Jul 3, 2014 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.