0

I've recently converted an application from using .NET Framework to .NET Core and in the process some of my endpoints have stopped producing the expected result due to escaping certain characters when returning them.

My controllers broadly look like this:

class MyController
{
    [HttpGet]
    [Authenticated]
    public async Task<ActionResult> GetMyObject(string id)
    {
        var myObj = // Controller specific code to look up the object
        return new JsonResult(myObj);
    }
}

This was previously returning a result like this:

{"HtmlTemplate":"
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
 <link href='https://fonts.googleapis.com/css?family=Nunito+Sans' rel='stylesheet' />
 <style>

Whereas now it looks like

{"htmlTemplate":"
\u003C!DOCTYPE html\u003E
\u003Chtml lang=\u0022en\u0022 xmlns=\u0022http://www.w3.org/1999/xhtml\u0022\u003E
\u003Chead\u003E
 \u003Clink href='https://fonts.googleapis.com/css?family=Nunito\u002BSans' rel='stylesheet' /\u003E
 
 \u003Cstyle\u003E

I have less control over modifying the caller of the endpoint, so I'd like to address that in this application. I'm familiar with how to change the formatting on a serializer, like here, but I don't know how to set the parameters here since it's implicit.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andy
  • 3,228
  • 8
  • 40
  • 65

1 Answers1

1

You need to configure JsonOptions:

using Microsoft.AspNetCore.Mvc;

// ...
builder.Services.Configure<JsonOptions>(options =>
    options.JsonSerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping);

Note that there are 2 JsonOptions, one from Microsoft.AspNetCore.Mvc namespace and one from Microsoft.AspNetCore.Http.Json namespace, for controllers you need the former one.

Another approach can be to serialize "manually" with needed settings and return ContentResult (to handle this on per endpoint basis if needed).

Guru Stron
  • 102,774
  • 10
  • 95
  • 132