1.6.3. Building a API and testing
--
1.Create Api folder in controller folder, right click -> Add -> Controller -> Web API 2 Controller - Empty
2.Paste in Global.asax:
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
3.Write code in controller:
private ApplicationDbContext _context; public CustomersController() { _context = new ApplicationDbContext(); } // GET /api/customers public IEnumerable<Customer> GetCustomers() { return _context.Customers.ToList(); } // GET /api/customers/1 public Customer GetCustomers(int id) { var customer = _context.Customers.SingleOrDefault(c => c.Id == id); if (customer == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return customer; } // POST /api/customers [HttpPost] public Customer CreateCustomers(Customer customer) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } _context.Customers.Add(customer); _context.SaveChanges(); return customer; } // PUT /api/customers/1 [HttpPut] public void UpdateCustomers(int id, Customer customer) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id); if (customerInDb == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } customerInDb.Name = customer.Name; customerInDb.Birthday = customer.Birthday; customerInDb.IsSubscribeToNesletter = customer.IsSubscribeToNesletter; customerInDb.membershipTypeId = customer.membershipTypeId; _context.SaveChanges(); } // PUT /api/customers/1 [HttpDelete] public void DeleteCustomers(int id) { var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id); if (customerInDb == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } _context.Customers.Remove(customerInDb); _context.SaveChanges(); }
4.Test API
Open the browser and type: http://localhost:3968/Api/Customers
use POSTman
post
set header
key: content-type
value: application/json
set body
{ "Name": "Sea123", "IsSubscribeToNesletter": true, "membershipType": null, "membershipTypeId": 2, "Birthday": "2001/12/11" }
Last updated