How do I create the fields in the ViewModel required for the Web API call?

I want to know if this is possible or how can I mark the fields of my class used as a parameter in my web API call? I can obviously do this manually as soon as I got the message, but I was hoping there was something built in the pipeline (for example in MVC in conjunction with jQuery which uses mandatory field annotations to automatically return to the UI showing required field notation), so I don't have to check everything manually.

Let's say I have the following ViewModel class:

public class PersonViewModel
{
  public string FirstName {get; set;}

  public string MiddleName {get; set;}

  public string LastName {get; set;}

}

      

Here is my simple Post method on PersonController

public HttpResponseMessage Post(PersonViewModel person)
{


}

      

Let's say you need fields FirstName

and LastName

, but not MiddleName

. I want to know if the call will automatically respond to the client with an HTTP 400 Bad Request or similar if the entity Person

does not have one of the required fields filled?

Essentially, I have to do all this work manually, or is there a way to automatically handle structure descriptor fields so I don't have a lot of validation code for required fields?

Manual way I try to avoid:

if (ModelState.IsValid)
{
  if (person.LastName == string.empty)
  {
     return Request.CreateResponse(HttpStatusCode.BadRequest);
  }

}

      

Any help is appreciated, thanks!

+3


source to share


1 answer


WebAPI has a validation function. You should be able to mark the FirstName and LastName properties as [Required] and then use the action filter at the bottom of this blog post to send an appropriate response:

http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx



You can learn more about WebAPI validation here:

http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

+6


source







All Articles