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

标签 c# json asp.net-core asp.net-core-webapi

我正在创建一个 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/

相关文章:

c# - jquery $.when 不通过母版页中的等待功能工作

c# - 数据表获取元组作为对象

c# - 在 Web 浏览器控件中调用 Javascript 测试单击

Jquery ui 自动完成用 ID 填充隐藏字段

java - 如何正确处理 Java 中 Bing 搜索 API 的响应?

c# - 在区域内时的 Blazor 路由和布局

asp.net-core - 获取错误 : Entity type 'Course' is defined with a single key property,,但 2 个值已传递给 'DbSet.Find' 方法

c# - 解码 Azure 移动服务 JWT token 时出现 JwtSecurityToken 异常

objective-c - RestKit ios - put - json 而不是编码形式

c# - .NET Core 中是否取代了 HttpContent.ReadAsAsync<T> 方法?