ASP.NET Web API(C#)实现简单增删改查

最近学习web Api,自己动手做出了一个小例子

1. 在vs2015中新建 ASP.NET WEB Application 项目

2.在“新ASP.NET MVC 4项目”对话框中,选择“Web API”并点击“OK”

3. 在Models文件夹,添加一个模型

  命名为Product.cs

编辑Product.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HelloWebApi2.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}

4. 添加仓储类

  在Models文件夹中,添加一个名为IProductRepository的仓储接口类,并编辑:

  在Models文件夹中,添加ProductRepository.cs类,用以实现此接口:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HelloWebApi2.Models
{
    public class ProductRepository : IProductRepository
    {
        private List<Product> products = new List<Product>();
        private int _nextId = 1;
        //初始化数据
        public ProductRepository()
        {
            Add(new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 });
            Add(new Product { Id = 2, Name = "Yp-yo", Category = "Yoys", Price = 3.75M });
            Add(new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M });
        } 
        //根据id查询数据
        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 IEnumerable<Product> GetAll()
        {
            return products;
        }

        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;
        }
    }
}

5. 添加控制器
  在Controllers文件夹中,添加一个名为ProductsController的控制器:

  注意:此控制器继承于ApiController

using HelloWebApi2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace HelloWebApi2.Controllers
{
    public class ProductsController : ApiController
    {
        // GET: Products

        static readonly IProductRepository repository = new ProductRepository();

        public IEnumerable<Product> GetAllProducts()
        {
            return repository.GetAll();
        }
        public Product GetProduct(int id)
        {
            Product item = repository.Get(id);
            if (item == null)
            {
                //throw new HttpResponseException(HttpStatusCode.NotFound);
                throw new Exception("查询的id不存在!");

            }
            return item;
        }
        public IEnumerable<Product>GetProductsByCategory(string category)
        {
            return repository.GetAll().Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
        }

        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;
        }
        //Update
        public void PutProduct(int id,Product product)
        {
            product.Id = id;
            if (!repository.Update(product))
            {
                //throw new HttpResponseException(HttpStatusCode.NotFound);
                throw new Exception("更新的数据出错!");
            }

        }
        //Delete
        public void DeleteProduct(int id)
        {
            Product item = repository.Get(id);
            if (item == null)
            {
                //throw new HttpResponseException(HttpStatusCode.NotFound);
                throw new Exception("删除的数据出错!");
            }
            repository.Remove(id);
        }
    }
}

6. 接下来,开始建立视图,便于测试
  每一个方法前都有一句注释,标识了该方法的针对的请求的类型(取决于方法的开头),以及要请求到该方法,需要使用的url。

  这些url是有规律的,见下图:

  为了方便,这里直接使用/Views/Home/Index.cshtml,删除所有初始内容,修改为下面内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script> $(document).ready(function () { var load = function () { $("#products").empty(); $.getJSON("/api/products/", function (data) { $.each(data, function (key, val) { var str = val.Name + ':$' + val.Price; var ele = $("<li id=" + val.Id + ">" + "<strong>" + val.Id + "</strong>" +". "+ str + "</li>") ele.appendTo($('#products')); }); }); }; load(); //用于保存用户输入数据 var Product = { create: function () { Id: ""; Name: ""; Category: ""; Price: ""; return Product; } } //添加一条记录 请求类型:POST 请求url: /api/Products //请求到ProductsController.cs中的 public HttpResponseMessage PostProduct(Product item) 方法 $("#addItem").click(function () { var newProduct = Product.create(); newProduct.Name = $("#name").val(); newProduct.Category = $("#category").val(); newProduct.Price = $("#price").val(); $.ajax({ url: "/api/Products", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(newProduct), success: function () { alert("添加成功!"); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); //先根据Id查询记录 请求类型:GET 请求url: /api/Products/Id //请求到ProductsController.cs中的 public Product GetProduct(int id) 方法 $("#showItem").click(function () { var inputId = $("#id2").val(); $("#name2").val(""); $("#category2").val(""); $("#price2").val(""); $.ajax({ url: "/api/Products/" + inputId, type: "GET", contentType: "application/json; charset=urf-8", success: function (data) { $("#name2").val(data.Name); $("#category2").val(data.Category); $("#price2").val(data.Price); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); //修改该Id的记录 请求类型:PUT 请求url: /api/Products/Id //请求到ProductsController.cs中的 public void PutProduct(int id, Product product) 方法 $("#editItem").click(function () { var inputId = $("#id2").val(); console.log(inputId) var newProduct = Product.create(); newProduct.Name = $("#name2").val(); newProduct.Category = $("#category2").val(); newProduct.Price = $("#price2").val(); $.ajax({ url: "/api/Products/" + inputId, type: "PUT", data: JSON.stringify(newProduct), contentType: "application/json; charset=urf-8", success: function () { alert("修改成功! "); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); //删除输入Id的记录 请求类型:DELETE 请求url: /api/Products/Id //请求到ProductsController.cs中的 public void DeleteProduct(int id) 方法 $("#removeItem").click(function () { var inputId = $("#id2").val(); $.ajax({ url: "/api/Products/" + inputId, type: "DELETE", contentType: "application/json; charset=uft-8", success: function (data) { alert("Id为 " + inputId + " 的记录删除成功!"); load(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("请求失败,消息:" + textStatus + " " + errorThrown); } }); }); }); </script>
    <div id="body">
        <div>
        <h1>All Products</h1>
        <ul id="products"></ul>
    </div>
        <section>
            <h2>添加记录</h2>
            Name:<input id="name" type="text" /><br />
            Category:<input id="category" type="text" />
            Price:<input id="price" type="text" /><br />
            <input id="addItem" type="button" value="添加" />
        </section>

        <section>
            <br />
            <br />
            <h2>修改记录</h2>
            Id:<input id="id2" type="text" /><br />
            Name:<input id="name2" type="text" /><br />
            Category:<input id="category2" type="text" />
            Price:<input id="price2" type="text" /><br />
            <input id="showItem" type="button" value="查询" />
            <input id="editItem" type="button" value="修改" />
            <input id="removeItem" type="button" value="删除" />
        </section>

    </div>
</body>
</html>

6. 最终效果如下:

你可能感兴趣的:(Web,api)