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

时间:2017-04-12 09:36:31

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

我正在创建一个应该接受JSON对象和简单类型的Web Api方法。但所有参数始终为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);
}

4 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

多个 [FromBody] 在Api中不起作用。请检查此Microsoft Official blog

所以现在你可以这样做,创建一个complex object,它应该包含你的oldCredentials和newPassword。例如,我的示例中的 LoginData 类。 myLoginRequest 是另一个对象类,它是 LoginData deserialized

[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

答案 2 :(得分:1)

根据Parameter Binding in ASP.NET Web API,&#34;最多允许一个参数从邮件正文中读取&#34;。意味着只有一个参数可以包含[FromBody]。所以在这种情况下,它将无法正常工作。创建一个复杂对象并向其添加所需的属性。您可以将newPassword添加到复杂对象中以使其正常工作。

答案 3 :(得分:0)

public class DocumentController : ApiController
{
    [HttpPost]
    public IHttpActionResult PostDocument([FromBody] Container data)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(data.Document)) return ResponseMessage(Request.CreateResponse(HttpStatusCode.NoContent, "No document attached"));

            return ResponseMessage(IndexDocument(data, Request));
        }
        catch (Exception ex)
        {
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.NotAcceptable, ex.Message));
        }
    }

}



public class InsuranceContainer
{
    [JsonProperty("token")]
    public string Token { get; set; }
    [JsonProperty("document")]
    public string Document { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }
}




var fileAsBytes = File.ReadAllBytes(@"C:\temp\tmp62.pdf");
String asBase64String = Convert.ToBase64String(fileAsBytes);


var newModel = new InsuranceContainer
    {
       Document = asBase64String,
       Text = "Test document",
    };

string json = JsonConvert.SerializeObject(newModel);

using (var stringContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json"))
    using (var client = new HttpClient())
    {
        var response = await client.PostAsync("https://www.mysite.dk/WebService/api/Document/PostDocument", stringContent);
        Console.WriteLine(response.StatusCode);
        var message = response.Content.ReadAsStringAsync();
        Console.WriteLine(message.Result);


    }