Performing CURD operations using Web API – Part 3

Posted by Anuraj on Sunday, September 1, 2013 Reading time :1 minute

.Net ASP.Net ASP.Net MVC Entity Framework Web API

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.

public class Employee
    public int Id { get; set; }
    [Required(ErrorMessage = "Name cannot be empty")]
    public string Name { get; set; }
    [Required(ErrorMessage = "Email cannot be empty")]
    [EmailAddress(ErrorMessage = "Valid email address required")]
    public string Email { get; set; }
        ErrorMessage = "Valid phone number required.")]
    public string Phone { get; set; }

And the Post method code like this.

public HttpResponseMessage Post(Employee employee)
    using (DataContext dataContext = new DataContext())
        if (ModelState.IsValid)
            var response = Request.CreateResponse<Employee>
                (HttpStatusCode.Created, employee);
            response.Headers.Location =
                new Uri(Url.Link("DefaultApi", new { id = employee.Id }));
            return response;
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

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.

Fiddler - POST request with Invalid Email address

And here is the response from Web API Service, in Fiddler.

Service response in Fiddler

Happy Programming

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.

Similar Posts

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon

BMC logoBuy me a coffee

Copyright © 2019 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub