Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make fields on ViewModel required for Web API call?

I want to know if it is possible or how can I mark fields on my class used as a parameter on my Web API call to be required? I obviously can do this manually once I have received the message, but I was hoping there was something built in the pipeline (like in MVC in combination with jQuery that uses required field annotations to automatically kick back to UI showing required field notations) 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 a PersonController

public HttpResponseMessage Post(PersonViewModel person)
{


}

Let's say the FirstName and LastName fields are required but not MiddleName. What I want to know is will the call automatically respond back to the client with a HTTP 400 Bad Request or similar if the Person object does not have one of the required fields populated?

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

Manual Way I'm trying to avoid:

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

}

Any help is appreciated, thanks!

like image 469
atconway Avatar asked Aug 30 '25 17:08

atconway


1 Answers

WebAPI does have a validation feature. 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 back an appropriate response:

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

You can read more about WebAPI validation here:

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

like image 168
Youssef Moussaoui Avatar answered Sep 03 '25 02:09

Youssef Moussaoui