Home > Net >  Sending Json raw content from ASP .Net Core controller
Sending Json raw content from ASP .Net Core controller

Time:10-05

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.

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!

CodePudding user response:

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

return Content(
  jsonDataset, 
  "application/json");
  • Related