Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sending Json raw content from ASP .Net Core controller

I want to send raw Json content in a string on ASP .Net Core controller output.

If I try to do it by returning the string itself double quotes in its content will be escaped and the client will not recognize it as a Json content but as a string. Eg. :

public async Task<ActionResult<MyClass>> Get()
{
    try
    {
        // here we build an object from a service with a complex dataset
        MyClass myObject = ...;  // business code here
        // serializing the object
        JsonSerializerOptions options = new()
        {
            WriteIndented = true,
            ReferenceHandler = ReferenceHandler.IgnoreCycles
        };

        string jsonDataset = JsonSerializer.Serialize<MyClass>(myObject , options);
        // or we could do simply for testing something like: jsonDataset = "{\"Id\"=10, \"Label\"=\"HelloWorld!\"}";
        // then we send it to the client
        return Ok(jsonDataset);
    } 
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}

I cannot deserialize the json, it is too complex with object lists referencing other objects.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I cannot use NewtonSoft library, it is a no-go for my project’s client. So no anonymous class for deserialization here :[|]

Is there a way to output the string "jsonObject" as an application/json content BUT WITHOUT double-quote escaping ?

Thanks for any help!

>Solution :

You can use the Content methods to return the string and specify the content type:

return Content(
  jsonDataset, 
  "application/json");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading