2017-04-12 131 views
3

我创建应该接受一个JSON对象和简单类型的Web API方法中的WebAPI模型。但是,所有参数总是nullJSON对象和简单类型使用FromBody

的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); 
} 
+0

是的,我使用邮递员来测试我的API。 – Kingpin

+0

请检查我的答案波纹管,让我知道它的工作或没有 –

+0

@Kingpin是否明确,如果使用asp.net-Web的API或asp.net核心 – Nkosi

回答

2

目前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); 
} 
+0

谢谢,创建帮助级梳理二者是解决办法。我习惯于在可能有多个参数的地方使用。 – Kingpin

+0

这是可能的。但是您发送数据和尝试访问参数的方式不匹配。这就是为什么他们总是空的。 – Nkosi

1

不止一个[FromBody]不阿比工作。检查这Microsoft Official blog

所以现在你可以这样做,创建一个complex object它应该包含您的oldCredentials和newPassword。对于我的例子波纹管例如LoginData类。而myLoginRequest是另一个对象类是deserializedLoginData

[HttpPut("UpdatePassword")] 
[Route("WebServices/UsersService.svc/rest/users/user")] 
public void UpdatePassword([FromBody]LoginData MyCredentials) 
{ 
loginRequest request = JsonConvert.DeserializeObject<myLoginRequest> 
          (json.ToString()); 

// then you can do the rest 
1

作为每Parameter Binding in ASP.NET Web API“至多一个参数被允许从消息主体来读取”。意味着只有一个参数可以包含[FromBody]。所以在这种情况下,它不会工作。创建一个复杂的对象并为其添加必需的属性。您可以将newPassword添加到复杂的对象以使其工作。