“JSON 值无法转换为 System.Nullable'1[System.Int32]。小路: $.pin |行号:7 |BytePositionInLine:20。

"The JSON value could not be converted to System.Nullable`1[System.Int32]. Path: $.pin | LineNumber: 7 | BytePositionInLine: 20."

提问人:Nikusha Gabidzashvili 提问时间:11/8/2023 更新时间:11/9/2023 访问量:44

问:

所以我使用 asp net 创建 web api 并使用 swagger ui,当我尝试发布像注册用户这样的数据时,我收到以下错误:

response status 400
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-2eab5ca50f25670cbaae859bf26f0968-6647b29cdb08df1a-00",
  "errors": {
    "userRegister": [
      "The userRegister field is required."
    ],
    "$.pin": [
      "The JSON value could not be converted to System.Nullable`1[System.Int32]. Path: $.pin | LineNumber: 7 | BytePositionInLine: 20."
    ]
  }
}

这是我试图发布的内容:

{
  "email": "[email protected]",
  "firstname": "test",
  "lastname": "test",
  "phone": 511223170,
  "accountType": 1,
  "iban": "GE05258155379184328548",
  "pin": 12345678901,
  "password": "qazwsxplmokn"
}

当我不更改该值中的任何内容并将它们保留为“字符串”或 intiger 0 时,它可以工作

这是请求代码:

        [HttpPost("Register")]
        public IActionResult Register(UserRegister userRegister)
        {
            if(_db.GetAll<string>($"select Email from dbo.Users where Email = '{userRegister.Email}'").Count() == 0)
            {
                if (_db.GetAll<string>($"select Phone from dbo.Users where Phone = {userRegister.Phone}").Count() == 0)
                {
                    byte[] passwordSalt = new byte[128 / 8];
                    using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
                    {
                        rng.GetNonZeroBytes(passwordSalt);
                    }

                    string PasswordSaltWithKey = _configuration.GetSection("AppSettings:PasswordKey") +
                       Convert.ToBase64String(passwordSalt);

                    byte[] passwordHash = KeyDerivation.Pbkdf2(
                        password: userRegister.Password,
                        salt: Encoding.ASCII.GetBytes(PasswordSaltWithKey),
                        prf: KeyDerivationPrf.HMACSHA256,
                        iterationCount: 100000,
                        numBytesRequested: 256 / 8
                    );

                    string addAuthSql = $@"
                        INSERT INTO dbo.Auth (
                            [Email],
                            [Phone],
                            [PasswordHash],
                            [PasswordSalt]
                        )VALUES(
                            '{userRegister.Email}',
                            {userRegister.Phone},
                            @PasswordHash,
                            @PasswordSalt)
";

                    string addUserSql = $@"
                        INSERT INTO dbo.Users(
                            [Email],
                            [Firstname],
                            [Lastname],
                            [Phone],
                            [AccountType],
                            [IBAN],
                            [PIN]
                        )VALUES(
                            '{userRegister.Email}',
                            '{userRegister.Firstname}',
                            '{userRegister.Lastname}',
                            {userRegister.Phone},
                            {userRegister.AccountType},
                            '{userRegister.IBAN}',
                            {userRegister.PIN}
                        )
                        ";

                    List<SqlParameter> sqlParameters = new List<SqlParameter>();


                    SqlParameter passwordSaltParameter = new SqlParameter("@PasswordSalt", SqlDbType.VarBinary);
                    passwordSaltParameter.Value = passwordSalt;

                    SqlParameter passwordHashParameter = new SqlParameter("@PasswordHash", SqlDbType.VarBinary);
                    passwordHashParameter.Value = passwordHash;

                    sqlParameters.Add(passwordSaltParameter);
                    sqlParameters.Add(passwordHashParameter);

                    if (_db.ExecuteWithParameters(addAuthSql, sqlParameters) && _db.Execute(addUserSql))
                    {
                        return Ok("Succesfully added user");
                    }
                    else
                    {
                        throw new Exception("ERROR");
                    }
                }
                return BadRequest($"PHONE_{userRegister.Phone}_ALREADY_EXISTS");
            }
            return BadRequest($"EMAIL_{userRegister.Email}_ALREADY_EXISTS");
        }

模型:

namespace Api.Models
{
    public class UserRegister
    {
        public string? Email { get; set; }
        public string? Firstname { get; set; }
        public string? Lastname { get; set; }
        public int Phone { get; set; }
        public int AccountType { get; set; }
        public string? IBAN { get; set; }
        public int PIN { get; set; }
        public string?  Password { get; set; }
    }
}

我以为这是因为命名,我尝试添加 [JsonPropertyName],但仍然不起作用,我在谷歌中找不到任何对我有帮助的东西

C# asp.net ASP.NET-Web-API

评论


答:

1赞 Dacovica 11/8/2023 #1

问题是您的引脚值(12345678901)高于可以保持的最大值(2147483647)。将图钉的类型更改为字符串(如果您的逻辑规定它可以同时包含字母、数字和特殊字符),添加最大值验证 ex:9999,或将类型更改为 .intlong

P.S:不要把所有的逻辑都放到控制器中,把它分成逻辑模块(服务、存储库、验证器等)。