Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return "raw" json in ASP.NET Core 2.0 Web Api

The standard way AFAIK to return data in ASP.NET Core Web Api is by using IActionResult and providing e.g. an OkObject result. This works fine with objects, but what if I have obtained a JSON string somehow, and I just want to return that JSON back to the caller?

e.g.

public IActionResult GetSomeJSON() {     return Ok("{ \"name\":\"John\", \"age\":31, \"city\":\"New York\" }"); } 

What ASP.NET Core does here is, it takes the JSON String, and wraps it into JSON again (e.g. it escapes the JSON)

Returning plain text with [Produces("text/plain")] does work by providing the "RAW" content, but it also sets the content-type of the response to PLAIN instead of JSON. We use [Produces("application/json")] on our Controllers.

How can I return the JSON that I have as a normal JSON content-type without it being escaped?

Note: It doesn't matter how the JSON string was aquired, it could be from a 3rd party service, or there are some special serialization needs so that we want to do custom serialization instead of using the default JSON.NET serializer.

like image 234
MichelZ Avatar asked Jan 19 '18 08:01

MichelZ


People also ask

How do I return JSON in Web API NET Core?

To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .

How do I get raw JSON data from REST API?

To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.

How do I return XML and JSON from Web API in .NET Core?

In order to return XML using an IActionResult method, you should also use the [Produces] attribute, which can be set to “application/xml” at the API Controller level. [Produces("application/xml")] [Route("api/[controller]")] [ApiController] public class LearningResourcesController : ControllerBase { ... }


1 Answers

And of course a few minutes after posting the question I stumble upon a solution :)

Just return Content with the content type application/json...

return Content("{ \"name\":\"John\", \"age\":31, \"city\":\"New York\" }", "application/json"); 
like image 89
MichelZ Avatar answered Oct 09 '22 09:10

MichelZ