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

时间:2016-02-26 17:21:34

标签: asp.net-web-api2

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

在Web API 2中,RegisterBindingModel类是

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类是

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 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方法的bound参数中为null。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是因为您发布了userApplicationUser&amp;只有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);