Just a record:
using ReallyTrue.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
namespace ReallyTrue
{
public class CustomersController : ApiController
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
}
public IEnumerable<Customer> GetCustomers()
{
var customer = _context.Customers.SingleOrDefault(c => c.Id = id);
}
public Customer GetCustomer(int id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customer == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return customer;
}
[HttpPost]
public Customer CreateCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
_context.Customers.Add(customer);
_context.SaveChanges();
return customer;
}
[HttpPut]
public void UpdateCustomer(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.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
customerInDb.MembershipType = customer.MembershipType;
_context.SaveChanges();
}
[HttpDelete]
public void DeleteCustomer(int id)
{
var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customerInDb == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
_context.Customers.Remove(customerInDb);
_context.SaveChanges();
}
}
}
Improvement of the code: We can replace ActionResult by IHttpActionResult, then
throw new HttpResponseException(HttpStatusCode.BadRequest)
can be replaced by
return BadRequest()
etc.
No comments:
Post a Comment