PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/MvcApplicationAPI/Controllers/ProductsController.cs

https://github.com/henrikjakobsen/WebAPI
C# | 76 lines | 65 code | 11 blank | 0 comment | 4 complexity | 336d25dfbcc267797435131f4d77cb23 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web;
  7. using System.Web.Http;
  8. using System.Web.Mvc;
  9. using MvcApplicationAPI.Models;
  10. using MvcApplicationAPI.Repositories;
  11. namespace MvcApplicationAPI.Controllers
  12. {
  13. public class ProductsController : ApiController
  14. {
  15. private ProductRepository _repository;
  16. public ProductsController()
  17. {
  18. _repository = new ProductRepository();
  19. }
  20. private static IEnumerable<Product> _products = new List<Product>()
  21. {
  22. new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
  23. new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
  24. new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
  25. };
  26. public IQueryable<Product> Get()
  27. {
  28. return _products.AsQueryable();
  29. }
  30. public Product GetProductById(int id)
  31. {
  32. var product = _products.FirstOrDefault((p) => p.Id == id);
  33. if (product == null)
  34. {
  35. throw new HttpResponseException(HttpStatusCode.NotFound);
  36. }
  37. return product;
  38. }
  39. public IEnumerable<Product> GetProductsByCategory(string category)
  40. {
  41. return _products.Where((p) => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
  42. }
  43. public HttpResponseMessage Post(Product product)
  44. {
  45. _repository.Add(product);
  46. var response = Request.CreateResponse<Product>(HttpStatusCode.Created, product);
  47. var uri = Url.Route(null, new { id = product.Id });
  48. response.Headers.Location = new Uri(Request.RequestUri, uri);
  49. return response;
  50. }
  51. public void Put(int id, Product product)
  52. {
  53. product.Id = id;
  54. if (!_repository.Update(product))
  55. {
  56. throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
  57. }
  58. }
  59. public HttpResponseMessage Delete(int id)
  60. {
  61. _repository.Remove(id);
  62. return new HttpResponseMessage(HttpStatusCode.NoContent);
  63. }
  64. }
  65. }