2

My request body is:

{
  "value": "b\\a",
}

When I read it at middleware level with body = await reader.ReadToEndAsync(); I am getting the same request body string.

BUT when I use the binded value in controller it has only one backslash.

[ProducesResponseType(201)]
[HttpPost("lol")]
public async Task<ActionResult> Create([FromBody] TokenDTO token)
{
    var a = token.value;
    if (a == "b\\\\a")
    {
        Console.WriteLine("EQUAL:" + a);
    }
    else
    {
        Console.WriteLine("NOT EQUAL:" + a);
    }

    return Created(token);
}

Here I am getting this response: NOT EQUAL:b\a

Is it some kind of bug? Or I should decode request body in some way?

I checked whether middleware does not corrupt it by removing it and the issue still remains.

Deivydas Voroneckis
  • 1,973
  • 3
  • 19
  • 40
  • 3
    The actual value is b\a. JSON puts a \ in front of the \ to escape it. So C# is showing the real value. https://stackoverflow.com/questions/19176024/how-to-escape-special-characters-in-building-a-json-string **In other words the C# is working 100% as expected. It is not corrupted**. – mjwills Dec 28 '20 at 13:07
  • @mjwills what I expect to get is a string containing \\ . Then how can I pass then this string from my client app that api would receive `b\\a` string(with two double backslashes)? – Deivydas Voroneckis Dec 28 '20 at 13:13
  • 3
    If the value is Matthew\Wills then the JSON will contain Matthew\\Wills. If Matthew\\Wills it will be Matthew\\\\Wills in the JSON. If your JSON has `{ "value": "b\\a", }` in it then the value is (no discussion, no debate) b\a. **If they didn't mean that, that is a bug in the caller not in the C#.** This is nothing to do with C# - it is how JSON escaping works - https://stackoverflow.com/questions/19176024/how-to-escape-special-characters-in-building-a-json-string . – mjwills Dec 28 '20 at 13:14
  • @mjwills thank you – Deivydas Voroneckis Dec 28 '20 at 13:22

0 Answers0