Performing CURD operations using Web API – Part 3

September 01, 2013 by Anuraj

.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

Copyright © 2024 Anuraj. 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. Powered by Jekyll. Hosted with ❤ by GitHub