2

I have an interesting issue. I have following model with required data annotation for some of the properties.

public class Consumer : MongoEntity
{
    public Consumer()
    {
        Products = new List<Product>();
    }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Address { get; set; }

    public string Phone { get; set; }

    [Required]
    public Location CurrentLocation { get; set; }

    public List<Product> Products { get; set; }

}

Now in my web api controller I am accepting this as a parameter as show below:

[Route("")]
[ValidateModel]
public IHttpActionResult Post([FromBody]Consumer consumer)
{
    try
    {
        if (ModelState.IsValid)
        {
            _consumerService.Create(consumer);
            return Ok("User created sucessfully.");  
        }

        return BadRequest("User object is not complete. It's missing mandatory fields");
    }
    catch
    {
        return InternalServerError(new Exception("Something went wrong while saving the data back to database."));
    }
}

I am under the impression that if any of the required field of consumer model is null model state should be false, but it always return true. Web api only sets model state null when i send an empty body to the controller. Is there any logical explanation to this? Why web api don't take account of required properties of complex argument type?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
qamar
  • 1,437
  • 1
  • 9
  • 12
  • Please refer http://stackoverflow.com/questions/17923622/modelstate-isvalid-even-when-it-should-not-be . I think this will give you an idea – Jayaraj.K Dec 26 '14 at 05:56
  • I read that it does not point to the correct reason its merely a hack – qamar Dec 26 '14 at 09:39

0 Answers0