zoukankan      html  css  js  c++  java
  • .net Api 接口调用 增删改查

    .net Api项目搭建内容以前已经说过了,文章链接,这篇文章在已经搭建好项目基础上简单说下如何建立API增删改查接口。


    在Models中建立一个实体类:

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

    处理数据的接口放在Models中:

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

    业务处理的接口实现类也放在Models中:

    namespace ApiTest.Models
    {
        public class ProductRepository:IProductRepository
        {
            private List<Product> products = new List<Product>();
            private int _nextId = 1;
            public ProductRepository()
            {
                products.Add(new Product { Id = 0, Name = "Tomato soup", Category = "Groceries", Price = 1.39M });
                products.Add(new Product { Id = 1, Name = "Yo-yo", Category = "Toys", Price = 3.75M });
                products.Add(new Product { Id = 2, 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;
            }
        }

    在Controllers中新建ProductController:

    //这里路由处理根据http协议
    namespace ApiTest.Controllers
    {
        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=Groceries
            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 });
                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);
            }
        }

    在Views中的Home中修改原有的index文件:

    <script src="~/Content/jquery-3.1.1.js"></script>
    <div id="body">
        <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>
    <script>
        //用于保存用户输入数据
        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("添加成功!");
                },
                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);
                },
                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();
            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);
                }
            });
        });
    
        //删除输入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 + " 的记录删除成功!");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("请求失败,消息:" + textStatus + "  " + errorThrown);
                }
            });
        });
    </script>

    启动项目,进入home的index页面,这里会对Api接口进行请求操作。
    这里写图片描述

  • 相关阅读:
    Java 常用工具类
    Shiro 分析
    Oracle 恢复表操作内容
    Struts2 中的配置文件 package name 、namespace 以及 对象方法调用
    MySql 修改字符集
    命名空间、静态函数、实例函数
    Eclipse Tomcate 热部署
    Java Json
    Mybatis 存储过程调用
    HDFS源码分析心跳汇报之数据结构初始化
  • 原文地址:https://www.cnblogs.com/wangqilong/p/10088367.html
Copyright © 2011-2022 走看看