Web API Example: ProductsController

Here's an example Web API controller that exposes a simple data object through Entity Framework's Code First feature. To support this example, we will need three files:

  • The modelProduct.cs (Listing 11-3)
  • The database contextDataContext.cs (Listing 11-4)
  • The Web API controllerProductsController.cs (Listing 11-5)

Listing 11.3: Product.cs

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int UnitsInStock { get; set; }
}

Listing 11.4: DataContext.cs

public class DataContext : DbContext
{
    public DbSet<Product> Products { get; set; }
}

Listing 11.5: ProductsController.cs

public class ProductsController : ApiController { private DataContext db = new DataContext(); // GET api/Products public IEnumerable<Product> GetProducts() { return db.Products; } // GET api/Products/5 public Product GetProduct(int id) { Product product = db.Products.Find(id); if (product == null) { throw new HttpResponseException( Request.CreateResponse( HttpStatusCode.NotFound)); } return product; } // PUT api/Products/5 public HttpResponseMessage PutProduct(int id, Product product) { if (ModelState.IsValid && id == product.ID) { db.Entry(product).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return Request.CreateResponse( HttpStatusCode.NotFound); } return Request.CreateResponse( HttpStatusCode.OK, product); } else { return Request.CreateResponse( HttpStatusCode.BadRequest); ...

Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.