Files
Vidly2/Vidly/Controllers/Api/CustomersController.cs
2019-01-24 23:30:41 +01:00

84 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Vidly.Models;
namespace Vidly.Controllers.Api
{
public class CustomersController : ApiController
{
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 GetCustomer(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 CreateCustomer(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 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.BirthDate = customer.BirthDate;
customerInDb.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;
customerInDb.MembershipTypeId = customer.MembershipTypeId;
_context.SaveChanges();
}
// DELETE /Api/Customers/1
[HttpDelete]
public void DeleteCustomer(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();
}
}
}