0

I have this code

    [Fact]
    public void TestContactNew()
    {
        var options = new JsonSerializerOptions
        {
            Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
            WriteIndented = true
        };
        string aplus = "A+";
        string json = JsonSerializer.Serialize(aplus, options).ToString();
        Console.WriteLine("{0} {1}", aplus, json);
    }

It outputs

A+ "A\u002B"

When I expect

A+ "A+"

What I'm doing wrong?

I uploaded the code here https://github.com/dhilst/csharp-test3

To run on console I use this dotnet test --logger:"console;verbosity=detailed"

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
geckos
  • 5,687
  • 1
  • 41
  • 53
  • Probably a duplicate of [dotnet core System.Text.Json unescape unicode string](https://stackoverflow.com/q/58003293/3744182), please check. – dbc May 12 '20 at 14:36
  • 1
    [`System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping`](https://learn.microsoft.com/en-us/dotnet/api/system.text.encodings.web.javascriptencoder.unsaferelaxedjsonescaping?view=netcore-3.1#System_Text_Encodings_Web_JavaScriptEncoder_UnsafeRelaxedJsonEscaping) from the above answer does work, see https://dotnetfiddle.net/O19XWo. Looks like a duplicate. – dbc May 12 '20 at 14:46
  • For some discussion about why Microsoft did this see https://github.com/dotnet/runtime/issues/35281 and https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#minimal-character-escaping – dbc May 12 '20 at 15:15
  • What are the security concerns about plus sign? It is considered HTML or something like that? I can't find anything about what characters would be escaped. – geckos May 13 '20 at 15:12
  • Thanks for the references, it seems that this is the expected behavior and it's about some security concerns, but I can't find what – geckos May 13 '20 at 15:14
  • I think the security concerns arise when the JSON is embedded in HTML or a ` – dbc May 13 '20 at 16:02
  • I found this: [Security benefits of encoding HTML special characters in JSON responses](https://stackoverflow.com/q/13236415/3744182). – dbc May 13 '20 at 16:27
  • Thanks @dbc, in fact if there is a security concert and MS take care of this fore me I would like to use the safer option. Thanks for your explanation, I never thought about this, lots of JSON fields are simply rendered in HTML, and this may be an XSS attack vector, thanks again! – geckos May 13 '20 at 18:38

0 Answers0