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

C#Jsonasp.net Mvcasp.net Core-Mvc

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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");

Solution 2 - C#

In your action, replace Ok() with the Content() method, which lets you set the content (raw content), content type, and status code of your response: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.contentresult?view=aspnetcore-2.0

Solution 3 - C#

This worked for me, where Json() did not:

return new JsonResult(json);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichelZView Question on Stackoverflow
Solution 1 - C#MichelZView Answer on Stackoverflow
Solution 2 - C#Arash MotamediView Answer on Stackoverflow
Solution 3 - C#Oliver BockView Answer on Stackoverflow