简体   繁体   中英

how to get ModelState working on asp.net mvc web api?

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 Required , StringLenght etc... I have the post method like this:

public HttpResponseMessage Post([FromBody] ProductViewModel value)
{
   if (ModelState.IsValid)
   {
      // persist data here...

      return Request.CreateResponse(HttpStatusCode.OK);
   }

   return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}

I have the GetErrors() method as an extension to get an List<> of my errors and pass to the client. My question is: Why the ModelState does not work?

if I pass null into a property of my ViewModel this validation simply does not work. IsValid property is always true . Is there any way to work around this and get the ModelState work such as MVC ?

My Model looks like this:

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; }
}

Thank you.

Could you make sure that you are passing in the Content-Type as part of your request? (if content-type is not passed, a default value for the particular type is set and the model state would not be having errors...this bug has been fixed recently).

also, you could do the following:

return Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM