Return JSON string explicitly from Asp.net WEBAPI?

In some cases, I have NewtonSoft JSON.NET, and in my controller I just return a Jobject from my controller, and all is well.

But I have a case where I get some raw JSON from another service and must return it from my webAPI. In this context, I cannot use NewtonSOft, but if I could, I would create a JOBJECT from a string (which seems like unnecessary overhead processing) and return it, and everything will be fine with the world.

However, I want to return it simply, but if I return the string, then the client will receive a JSON wrapper with my context as an encoded string.

How can I explicitly return JSON from my WebAPI controller method?

+64
json asp.net-mvc asp.net-web-api
Jun 13 '13 at 21:56 on
source share
2 answers

There are several alternatives. The easiest way is to return your HttpResponseMessage method and create this response using StringContent based on your string, something similar to the code below:

 public HttpResponseMessage Get() { string yourJson = GetJsonFromSomewhere(); var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json"); return response; } 

And checking for null or empty JSON string

 public HttpResponseMessage Get() { string yourJson = GetJsonFromSomewhere(); if (!string.IsNullOrEmpty(yourJson)) { var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json"); return response; } throw new HttpResponseException(HttpStatusCode.NotFound); } 
+158
Jun 13 '13 at 22:02
source share

If you specifically want to return only JSON without using WebAPI features (for example, XML resolution), you can always write directly in the output. Assuming you host this using ASP.NET, you have access to the Response object, so you can write it this way as a string, then you don't need to actually return anything from your method - you already wrote the response text in output stream.

+2
Jun 13 '13 at 22:01
source share



All Articles