I couldn’t complete this series without mentioning the model validations part. Like normal services you can do custom validations, if validation fails, can create error responses and return. Similar to ASP.Net MVC, WebAPI also supports Model validations using DataAnnotations. And in the code you can use ModelState.IsValid property to validate Model is valid or not. For the validation purposes I modified the Employee model class like this.
And the Post method code like this.
In Web API, Request.CreateErrorResponse() method supports an overload which helps to return ModelState property.
Here is the Fiddler request, with invalid email address in POST body.
And here is the response from Web API Service, in Fiddler.
Did you like this article? Share it with your friends