用仓储模式,首先建立一个接口
interface IProductRepository { IEnumerable<Product> GetAll(); Product Get(int id); Product Add(Product item);
void Remove(int id);
bool Update(Product item); }
实现类
public class ProductRepository:IproductRepository {
private List<Product> products = new List<Product>(); private int _nextId = 1; public ProductRepository() { Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M }); Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M }); Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M }); }
public IEnumerable<Product> GetAll() {
return products; }
public Product Get(int id) {
return products.Find(p => p.Id == id); }
public Product Add(Product item) {
if (item == null) {
throw new ArgumentNullException("item"); } item.Id = _nextId++; products.Add(item); return item; }
public void Remove(int id) { products.RemoveAll(p => p.Id == id); }
public bool Update(Product item) {
if (item == null) {
throw new ArgumentNullException("item"); }
int index = products.FindIndex(p => p.Id == item.Id);
if (index == -1) {
return false; } products.RemoveAt(index); products.Add(item); return true; } }
响应代码:在默认情况下,这个Web API框架设置响应状态码为200(OK)。但是根据这个HTTP/1.1协议,当POST请求在创建一个资源时,这个服务端应该回复状态201(Created)。
//添加一条
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; }
//更新一条
public void PutProduct(int id, Product product)
{
product.Id = id; if (!repository.Update(product))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
public void DeleteProduct(int id)
{
Product item = repository.Get(id); if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
repository.Remove(id);
}
//按sting类型检索
public IEnumerable<Product> GetProductsByCategory(string category)
{
return repository.GetAll().Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
}
//按Id检索
public Product GetProduct(int id)
{
Product item = repository.Get(id); if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
//获取所有
public IEnumerable<Product> GetAllProducts() {
return repository.GetAll(); }
浙公网安备 33010602011771号