2

Is it possible to return self-created JSON from an controller action method, so that it is not additionally escaped by ASP Net Core?

Consider the following code:

[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class MyController : Controller
{
    [HttpPost]
    public async Task<ActionResult<string>> Post(ItemPostRequest itemPostRequest)
    {
        var result = await callStoredProcedureOnDatabase(itemPostRequest); // generates JSON directly on the database using SQL Server's FOR JSON clause

        return CreatedAtAction(nameof(GetItem),
            new { Id = result.Id },
            result.Json
            );
    }
}
  • If I remove the third line with [Produces("application/json")] I get the unescaped JSON as expected, but the Content-Type header is only set to text/plain.
  • If I leave the [Produces("application/json")] in place, the Content-Type is correctly set to application/json, but my JSON become escaped.

So, how can I return the result.Json without getting escaped while having a correct Content-Type header of application/json?

1 Answer 1

0

You will have to do something like the answer here: How to specify ContentType for Web API controller method

The producers attribute, forced the format to be json. JSon strings are escaped correctly, so the result us expected. Beware that all clients expect a specific format, so if you are returning json, it is suggested that you remove the escape characters. https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-5.0

The preceding [Produces] filter:

  • Forces all actions within the controller to return JSON-formatted responses.

  • If other formatters are configured and the client specifies a different format, JSON is returned.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.