WebApi

* 基础

https://blog.csdn.net/qq_36456952/article/details/62885273

1. demo

  - 新建web → webAPI项目,注:项目中会添加WebApiConfig.cs

  - WebApi请求不是具体的页面,而是控制器中的方法,控制器继承自ApiController,并且每一个方法都以get  post  put  delete开头

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }

    }
Product
    interface IProductRepository
    {
        IEnumerable<Product> GetAll();
        Product Get(int id);
        Product Add(Product item);
        void Remove(int id);
        bool Update(Product item);

    }
IProductRepository
    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 Product Add(Product item)
        {
            if(item == null)
            {
                throw new ArgumentNullException("item");
            }
            item.Id = _nextId++;
            products.Add(item);
            return item;
        }

        public Product Get(int id)
        {
            return products.Find(p => p.Id == id);
        }

        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;
        }
    }
ProductRepository
    /// <summary>
    /// WebApi请求不是具体的页面,而是控制器中的方法,控制器继承自ApiController,并且每一个方法都以get  post  put  delete开头
    /// get   【查询】从服务器获取数据;
    /// post  【添加】发送数据到服务器,创建一条数据,对服务器产生影响;
    /// put   【更新】从服务器端更新一条数据,对服务器产生影响;
    /// delete【删除】删除数据,对服务器产生影响
    /// </summary>
    public class ProductsController : ApiController
    {

        static readonly IProductRepository repository = new ProductRepository();

        //GET: /api/products
        public IEnumerable<Product> GetAllProducts()
        {
            return repository.GetAll();
        }

        //GET: /api/products/id
        public Product GetProduct(int id)
        {
            Product item = repository.Get(id);
            if (item == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return item;
        }

        //GET: /api/products?category=category
        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return repository.GetAll().Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
        }

        //POST: /api/products
        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 });  //http://localhost:3328/api/Products/5
            response.Headers.Location = new Uri(uri);
            //返回到页面
            return response;
        }

        //PUT: /api/products/id
        public void PutProduct(int id, Product product)
        {
            product.Id = id;
            if (!repository.Update(product))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        //Delete: /api/products/id
        public void DeleteProduct(int id)
        {
            Product item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            repository.Remove(id);
        }
    }
ProductsController
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<div id="body">
    <section>
        <h2>添加记录</h2>
        Name: <input id="name" type="text" /><br />
        Category: <input id="category" type="text" /><br />
        Price: <input id="price" type="text" /><br />
        <input id="addItem" type="button" value="添加" />
    </section>
    <br /><br />
    <section>
        <h2>修改记录</h2>
        Id: <input id="id2" type="text" /><br />
        Name: <input id="name2" type="text" /><br />
        Category: <input id="category2" type="text" /><br />
        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>
<script>
        //用于保存用户输入的数字
    var product = {
        create: function () {
            Id: "";
            Name: "";
            Category: "";
            Price: "";
            return product;
        }
    };

    //post添加
    $("#addItem").click(function () {
        var newProduct = product.create();
        newProduct.Name = $("#name").val();
        newProduct.Category = $("#category").val();
        newProduct.Price = $("#price").val();
        $.ajax({
            type: "post",
            url: "/api/Products",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(newProduct),
            success: function () {
                alert("添加成功!");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("请求失败,消息:" + textStatus + " " + errorThrown);
            }
        });
    });

    //get查询
    $("#showItem").click(function () {
        var inputId = $("#id2").val();
        $("#name2").val("");
        $("#category2").val("");
        $("#price2").val("");
        $.ajax({
            type: "get",
            url: "/api/Products/" + inputId,
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                $("#name2").val(data.Name);
                $("#category2").val(data.Category);
                $("#price2").val(data.Price);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("请求失败,消息:" + textStatus + " " + errorThrown);
            }
        });
    });

    //put修改
    $("#editItem").click(function () {
        var inputId = $("#id2").val();
        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("修改成功! ");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("请求失败,消息:" + textStatus + "  " + errorThrown);
            }
        });
    });

    //delete删除
    $("#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 + " 的记录删除成功!");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("请求失败,消息:" + textStatus + "  " + errorThrown);
            }
        });
    });

</script>
Home/index.cshtml

 

posted on 2018-08-06 14:21  莫伊筱筱  阅读(190)  评论(0编辑  收藏  举报