Home > Software engineering >  ASP.NET Core 5 Response Json and Input JSON encoding issue
ASP.NET Core 5 Response Json and Input JSON encoding issue

Time:09-30

I have the following API,

    public class MyApiClass
    {
        public string Str { get; set; }
    }

    [AllowAnonymous]
    [HttpPost("myApi", Name = "MyApi2")]
    public IActionResult MyApi(MyApiClass myClassInput)
    {
        var obj = new MyApiClass
        {
            Str = "h24KFS69\\pucBJH3x2ov MAj\\/JWq/UBt3EjhKGUtBM="
        };
        return Ok(obj);
    }

I will call this API in Postman I will get the below response,

{
    "str": "h24KFS69\\pucBJH3x2ov MAj\/JWq/UBt3EjhKGUtBM="
}

Then I will call the same API using the same but as input,

{
    "str": "h24KFS69\\pucBJH3x2ov MAj\/JWq/UBt3EjhKGUtBM="
}

Then I checked,

>>> myClassInput.Str
"h24KFS69\\pucBJH3x2ov MAj/JWq/UBt3EjhKGUtBM="
>>> obj.Str
"h24KFS69\\pucBJH3x2ov MAj\\/JWq/UBt3EjhKGUtBM="
>>> myClassInput.Str == obj.Str
false

I am sending whatever I am getting in JSON response. Why they are different strings?

Interestingly, if you peak both values,

enter image description here

enter image description here

and test in JS,

>>> "h24KFS69\pucBJH3x2ov MAj\/JWq/UBt3EjhKGUtBM=" === "h24KFS69\pucBJH3x2ov MAj/JWq/UBt3EjhKGUtBM="
true

CodePudding user response:

In your API method try to make the string verbatim:

Str = @"h24KFS69\pucBJH3x2ov MAj\/JWq/UBt3EjhKGUtBM="

CodePudding user response:

Just found out that PostMan have pretty and raw response modes.

Pretty mode converting,

{
    "str": "h24KFS69\\pucBJH3x2ov MAj\\/JWq/UBt3EjhKGUtBM="
}

into

{
    "str": "h24KFS69\\pucBJH3x2ov MAj\/JWq/UBt3EjhKGUtBM="
}

I needed to use Raw mode.

Filed an issue with Postman as well https://github.com/postmanlabs/postman-app-support/issues/11307

  • Related