Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Web api crud operations

1,954 views

Published on

Web api crud operations

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Web api crud operations

  1. 1. Web API CRUDOperations Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com
  2. 2. Expert Days 2012 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  3. 3. HTTP Methods  GET ( retrieves )  PUT ( updates )  POST ( creates )  DELETE© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  4. 4. Repository Pattern  Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  5. 5. Getting a Resource (GET) public IEnumerable<Product> GetAllProducts() return repository.GetAll(); public Product GetProduct(int id) Product item = repository.Get(id); if (item == null) throw new HttpResponseException( new HttpResponseMessage(HttpStatusCode.NotFound)); return item;© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  6. 6. Creating a Resource (POST) public HttpResponseMessage PostProduct(Product item) { item = repository.Add(item); var response = Request .CreateResponse<Product>(HttpStatusCode.Created, item); string uri = Url.Link("DefaultApi", new { id = item.Id }); response.Headers.Location = new Uri(uri); return response;© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  7. 7. Updating a Resource (PUT) public void PutProduct(int id, Product contact) contact.Id = id; if (!repository.Update(contact)) throw new HttpResponseException( new HttpResponseMessage(HttpStatusCode.NotFound));© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  8. 8. Deleting a Resource public HttpResponseMessage DeleteProduct( int id ) repository.Remove(id); return new HttpResponseMessage( HttpStatusCode.NoContent );© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  9. 9. Web API CRUD Operations© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

×