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

C# JSON对象和简单类型使用FromBody在WebAPI中建模,c#,json,asp.net-core,asp.net-core-webapi,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, "SaveCredential

我正在创建一个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);
}

不止一个[FromBody]在Api中不工作。检查这个

现在您可以这样做了,创建一个
复杂对象
,它应该包含您的旧凭证和新密码。例如,我下面的示例中的LoginData类。myLoginRequest是另一个对象类,它将
反序列化
您的登录数据

[HttpPut(“UpdatePassword”)]
[路由(“WebServices/UsersService.svc/rest/users/user”)]
public void UpdatePassword([FromBody]LoginData MyCredentials)
{
loginRequest请求=JsonConvert.DeserializeObject
(json.ToString());
//然后你可以做剩下的事

根据“最多允许从消息正文读取一个参数”。表示只有一个参数可以包含[FromBody]。因此,在这种情况下它将不起作用。创建一个复杂对象并向其添加所需的属性。您可以向复杂对象添加新密码以使其起作用。

您正在向以下类发送映射的当前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);
}

是的,我用邮递员来测试我的api。请检查我下面的回答,让我知道它是否正常工作not@Kingpin,澄清是使用asp.net-web-api还是asp.net-Core我正在使用web api模板创建asp.net Core web应用程序。因为它只是一个rest服务。谢谢,创建一个结合两者的帮助类是解决方案。我已习惯于wcf其中可能有多个参数。这是可能的。但您发送数据和尝试访问参数的方式不匹配。这就是为什么它们始终为空。
[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);
}
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);


    }