简体   繁体   中英

Dotnet Core Web API escapes backslahes unintentionally

I have an endpoint that accepts json data of the currentPassword , newPassword and newPasswordConfirmation .

I've run into a problem, as I want to accept literal backslashes ( \ ) in passwords, they have to be passed in, but they get escaped by Web API validation.

I guess I'm missing so attribute on the C# class, but I haven't found it.

Request:

curl -X POST "https://localhost:44343/1/NO/User/123/Password/Change" -H "accept: application/json" -H "X-Api-Key: secret-key" -H "Content-Type: application/json" -d "{ \"currentPassword\": \"bla\hej\.%", \"newPassword\": \"blabla\", \"newPasswordConfirmation\": \"blabla\"}"

Response:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|3876e18a-40326202f78c6022.",
  "errors": {
    "$.currentPassword": [
      "'h' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.currentPassword | LineNumber: 1 | BytePositionInLine: 26."
    ]
  }
}

Model I deserialize to :

    public class BasePasswordModel
    {
        [Required]
        public string NewPassword { get; set; }
        [Required]
        public string NewPasswordConfirmation { get; set; }
    }

    public class ChangePasswordModel : BasePasswordModel
    {
        [Required]
        public string CurrentPassword { get; set; }
    }

If acceptting literal backslashes (\) in passwords, you need to use

\\  (Backslash character)

Other special character

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\t  Tab
\"  Double quote

Then the bakend can receive double backslash, because the particularity of the backslash, it must appear in pairs. The backslash in the database can be compared directly after it becomes a string.


The another method is to put the data into the formdata , it can serilize all charater.

public IActionResult change([FromForm]ChangePasswordModel changePasswordModel)
    {
        //...
        return Ok(changePasswordModel);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM