Home > Net >  React .NET - Client returns user string with double qoute marks and slash
React .NET - Client returns user string with double qoute marks and slash

Time:06-20

I am working with a project and I have 2 endpoints now where an admin can make a user an admin or remove the user as an admin.

This operation is made with the users ID. But when I enter the button to make/remove an admin, the user ID doesnt return as expected and it gives me a 500 error instead.

This is the Id I get

"\"65efe6a5-1384-49f7-8519-8d6789d26baf\""

This is the Id I need

"65efe6a5-1384-49f7-8519-8d6789d26baf"

What might be causing this and how could it be fixed?

backend

[HttpPost("assignAdminClaim")]
        //[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "IsAdmin")]
        public async Task<ActionResult> AssignAdminClaim([FromBody] string userId)
        {
            var user = await userManager.FindByIdAsync(userId);
            await userManager.AddClaimAsync(user, new Claim("role", "admin"));
            return NoContent();
        }

Frontend

const assignAdminClaim = async (id: string) => {
        await adminClaim(`${UrlUsers}/assignAdminClaim`, id)
    }

    const adminClaim = async (url: string, id: string) => {
        await axios.post(url, JSON.stringify(id), {
            headers: {
                "Content-Type": "application/json"
            }
        });

        Swal.fire({
            title: "Success",
            text: "Successfully updated",
            icon: "success",
        })
    }

All help would be much appreciated!

Thanks

CodePudding user response:

[![enter image description here][1]][1]

As you confirmed that JSON.stringify() is the cause, therefore I tried this code in the browser console and figured out that JSON.stringify() wraps strings with extra double quotes, check the attached image. [1]: https://i.stack.imgur.com/nDOGK.png

CodePudding user response:

Thanks to Mahmoud Nasr's comment, I managed to solve the issue. I dont know why, but it appears to be the JSON.stringify() that was the cause of the issue. If any one would have more knowledge about why, please let me know!

  • Related