gpt4 book ai didi

c# - 使用 FromBody 在 WebAPI 中建模的 JSON 对象和简单类型

转载 作者:行者123 更新时间:2023-12-01 23:43:20 29 4
gpt4 key购买 nike

我正在创建一个 Web Api 方法,该方法应该接受 JSON 对象和简单类型。但所有参数始终为null

我的 json 看起来像

{
"oldCredentials" : {
"UserName" : "user",
"PasswordHash" : "myCHqkiIAnybMPLzz3pg+GLQ8kM=",
"Nonce" : "/SeVX599/KjPX/J+JvX3/xE/44g=",
"Language" : null,
"SaveCredentials" : false
},
"newPassword" : "asdf"}

我的代码如下:

[HttpPut("UpdatePassword")]
[Route("WebServices/UsersService.svc/rest/users/user")]
public void UpdatePassword([FromBody]LoginData oldCredentials, [FromBody]string newPassword)
{
NonceService.ValidateNonce(oldCredentials.Nonce);

var users = UserStore.Load();
var theUser = GetUser(oldCredentials.UserName, users);

if (!UserStore.AuthenticateUser(oldCredentials, theUser))
{
FailIncorrectPassword();
}

var iv = Encoder.GetRandomNumber(16);
theUser.EncryptedPassword = Encoder.Encrypt(newPassword, iv);
theUser.InitializationVektor = iv;

UserStore.Save(users);
}

最佳答案

您当前发送的 JSON 映射到以下类

public class LoginData {
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string Nonce { get; set; }
public string Language { get; set; }
public bool SaveCredentials { get; set; }
}

public class UpdateModel {
public LoginData oldCredentials { get; set; }
public string newPassword { get; set; }
}

[FromBody] 只能在操作参数中使用一次

[HttpPut("WebServices/UsersService.svc/rest/users/user")]
public void UpdatePassword([FromBody]UpdateModel model) {
LoginData oldCredentials = model.oldCredentials;
string newPassword = model.newPassword;
NonceService.ValidateNonce(oldCredentials.Nonce);

var users = UserStore.Load();
var theUser = GetUser(oldCredentials.UserName, users);

if (!UserStore.AuthenticateUser(oldCredentials, theUser)) {
FailIncorrectPassword();
}

var iv = Encoder.GetRandomNumber(16);
theUser.EncryptedPassword = Encoder.Encrypt(newPassword, iv);
theUser.InitializationVektor = iv;

UserStore.Save(users);
}

关于c# - 使用 FromBody 在 WebAPI 中建模的 JSON 对象和简单类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43365791/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com