Reputation: 221
I am creating an Web API 2 application and a separate MVC client as there will be mobile apps also accessing the Web API 2 application.
In the Web API 2 the RegisterBindingModel class is
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; }
}
In the client the RegisterBinderModel class is
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; }
}
In my MVC client I am trying to register a new user.
// 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);
The register post method is
// 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);
}
The problem that I am experiencing is that only the email value is bound in the Web API register method. The password and confirmpassword values are null in the bound parameter of the my post method. Any ideas why?
Upvotes: 0
Views: 341
Reputation: 47375
It's because you are posting user
which an ApplicationUser
& only has its Email
property set:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
HttpClient test = new HttpClient();
HttpResponseMessage result2 = await test.PostAsJsonAsync(url, user);
Try posting the model
instead.
HttpResponseMessage result2 = await test.PostAsJsonAsync(url, model);
Upvotes: 1