title: how to get ModelState working on asp.net mvc web api?
body: <p>It is the first I have been using the asp.net mvc webApi, and I have Post/Put methods that has a parameter called ProductViewModel. Some properties of this ViewModel has data annotations to validate such as <code>Required</code>, <code>StringLenght</code> etc... I have the post method like this:</p>
  
  <pre><code>public HttpResponseMessage Post([FromBody] ProductViewModel value)
  {
     if (ModelState.IsValid)
     {
        // persist data here...
  
        return Request.CreateResponse(HttpStatusCode.OK);
     }
  
     return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
  }
  </code></pre>
  
  <p>I have the <code>GetErrors()</code> method as an extension to get an <code>List&lt;&gt;</code> of my errors and pass to the client. My question is: Why the ModelState does not work?</p>
  
  <p>if I pass null into a property of my ViewModel this validation simply does not work.  <code>IsValid</code> property is always <code>true</code>. Is there any way to work around this and get the ModelState work such as MVC ?</p>
  
  <p>My Model looks like this:</p>
  
  <pre><code>public class ProductViewModel
  {
      [Display(ResourceType = typeof(Resources.Global), Name = "Name")]
      [Required(ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Required")]
      [StringLength(100, ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Range")]
      public string Name { get; set; }
  
      [Display(ResourceType = typeof(Resources.Global), Name = "ShortName")]
      [Required(ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Required")]
      [StringLength(20, ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "Range")]
      public string ShortName { get; set; }
  }
  </code></pre>
  
  <p>Thank you.</p>