你能使用 Npgsql 将 C# byte[] 转换为 postgressql bytea吗

问题描述 投票:0回答:0

所以我在将

byte[]
转换为 postgres 中的
bytea
时遇到问题。我有一个程序接受密码(字符串),使用 HMACSHA512 将其转换为 byte[]。我想将我的
byte[]
数据插入到我的 postgres 数据库中。

插入语句

public static int Insert(User user)
    {
      string sqlcommand = $"INSERT INTO \"{Settings.UserTable}\" (userName, surname, email, passwordhash, passwordsalt, status) VALUES (@name, @surname, @email, encode(E'@passwordhash'::bytea, 'escape'), @passwordsalt::bytea, 0::bit)";
      using (NpgsqlCommand command = new NpgsqlCommand(sqlcommand, DatabaseConnection.Connection))
      {

        command.Parameters.AddWithValue("name", user.Name);
        command.Parameters.AddWithValue("surname", user.Surname);
        command.Parameters.AddWithValue("email", user.Email);
        command.Parameters.AddWithValue("passwordhash", user.PasswordHash);

        int result = (int)command.ExecuteNonQuery();
        return result;
      }
    }

型号

    public class User
    {
        [Required]
        public string Email { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Surname { get; set; }
        [Required]
        public byte[] PasswordSalt { get; set; }
        [Required]
        public byte[] PasswordHash { get; set; }
        
        public int status { get; set; }

        public string Token { get; set; }
        public DateTime TokenCreated { get; set; }
        public DateTime TokenExpires { get; set; }

        public User()
        {
            
        }

        public User(string name, string surname, string email, byte[] passwordHash, byte[] passwordSalt)
        {
            this.Name = name;
            this.Surname = surname;
            this.Email = email;
            this.PasswordHash = passwordHash;
            this.PasswordSalt = passwordSalt;
        }

这是我的控制器

[HttpPost("Register")]
        public IActionResult Register([FromBody] Register model)
        {
            var user = new User { Name = model.Name, Surname = model.Surname, Email = model.Email};


            using (HMACSHA512? hmac = new HMACSHA512())
            {
                user.PasswordSalt = hmac.Key;
                user.PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(model.Password));
            }

            UserQuery.Insert(user);

            return Ok(user);
        }

我的问题是它一直给我这个错误

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.InvalidOperationException: Parameter 'name' must have either its NpgsqlDbType or its DataTypeName or its Value set

我假设这与 passwordHash 和 passwordSalt 的转换有关

c# postgresql npgsql
© www.soinside.com 2019 - 2024. All rights reserved.