Performing CURD operations using Web API – Part 3

Posted by Anuraj on Sunday, September 1, 2013

.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; }
    [RegularExpression(@"[0-9]*$",
        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)
        {
            dataContext.Employees.Add(employee);
            dataContext.SaveChanges();
            var response = Request.CreateResponse<Employee>
                (HttpStatusCode.Created, employee);
            response.Headers.Location =
                new Uri(Url.Link("DefaultApi", new { id = employee.Id }));
            return response;
        }
        else
        {
            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


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe
Archives


Copyright © 2017 - 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