Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

c# - 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": "blahej.%", "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; }
    }
question from:https://stackoverflow.com/questions/65917353/dotnet-core-web-api-escapes-backslahes-unintentionally

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

\  (Backslash character)

Other special character

  Backspace (ascii code 08)
f  Form feed (ascii code 0C)

  New line

  Carriage return
  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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...