Web API 2 参数绑定缺少一些值

Web API 2 parameter binding missing some values

我正在创建一个 Web API 2 应用程序和一个单独的 MVC 客户端,因为移动应用程序也会访问 Web API 2 应用程序。

在网络中 API 2 RegisterBindingModel class 是

public class RegisterBindingModel
{
    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

在客户端中,RegisterBinderModel class 是

public class RegisterBindingModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

在我的 MVC 客户端中,我正在尝试注册一个新用户。

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterBindingModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

            System.Diagnostics.Debug.Print(model.Email);
            System.Diagnostics.Debug.Print(model.Password);
            System.Diagnostics.Debug.Print(model.ConfirmPassword);
            System.Diagnostics.Debug.Print(url);

            HttpClient test = new HttpClient();

            HttpResponseMessage result2= await  test.PostAsJsonAsync(url, user);

注册post方法是

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        System.Diagnostics.Debug.Print(model.Email);
        System.Diagnostics.Debug.Print(model.Password); // Is null?
        System.Diagnostics.Debug.Print(model.ConfirmPassword); //Is null?

        if (!ModelState.IsValid) // Is of course false
        {
            return BadRequest(ModelState);
        }

我遇到的问题是在 Web API 注册方法中只绑定了电子邮件值。 my post 方法的绑定参数中的 password 和 confirmpassword 值为空。有什么想法吗?

这是因为您发布的 user 其中一个 ApplicationUser 并且只有 Email 属性 集:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
HttpClient test = new HttpClient();
HttpResponseMessage result2 = await test.PostAsJsonAsync(url, user);

尝试发布 model

HttpResponseMessage result2 = await test.PostAsJsonAsync(url, model);