关于ASP.NET WebApi (增删改查)

1、首先,我们先来介绍一下什么是WebApi
ASP.NET Web API 是一种框架,用于轻松构建可以由多种客户端(包括浏览器和移动设备)访问的 HTTP 服务。ASP.NET Web API 是一种用于在 .NET Framework 上构建 RESTful 应用程序的理想平台。

可以把WebApi看成Asp.Net项目类型中的一种,其他项目类型诸如我们熟知的WebForm项目,Windows窗体项目,控制台应用程序等。

2、先来看一下这个demo的运行效果

这里写图片描述

如图所示,可以添加一条记录; 输入记录的Id,查询出该记录的其它信息; 修改该Id的记录; 删除该Id的记录。

3、开始建项目
1)新建一个“ASP.NET Web 应用程序”项目,命名为“Product”,点击确定,如图
这里写图片描述

2)和MVC类型的项目相似,构建程序的过程是先建立数据模型(Model)用于存取数据, 再建立控制器层(Controller)用于处理发来的Http请求,最后构造显示层(View)用于接收用户的输入和用户进行直接交互。
这里我们先在Models文件夹中建立产品Product类: Product.cs,如下:

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

namespace demoApi.Models
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
        public decimal Salary { get; set; }
    }
}

3)创建完一个Product类后,我们要编写一个类对其实现增删改查。
为了方便拓展和调用,我们在Product上构建一个接口“IProductRepository.cs ”,约定增删查改的方法和参数,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

4)然后,我们实现这个接口,在Models文件夹中新建一个类,具体针对Product类型的对象进行增删改查存取数据,并在该类的构造方法中,向List列表中存入几条数据,这个类叫:ProductRepository.cs,如下:

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

namespace demoApi.Models
{
    public class ProductRepository : IProductRepository
    {
        private List<Product> products = new List<Product>();
        private int nextId = 1;
        public ProductRepository()
        {
            Add(new Product { Name = "LLL", Department = "FD", Salary = 3000 });
            Add(new Product { Name = "CCC", Department = "HR", Salary = 6500 });
            Add(new Product { Name = "MMM", Department = "R&D", Salary = 10000 });
        }
        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(u=>u.ID==id);
        }

        public IEnumerable<Product> GetAll()
        {
            return products;
        }

        public void Remove(int id)
        {
            products.RemoveAll(u => u.ID == id);
        }

        public bool Update(Product item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            var index = products.FindIndex(u => u.ID == item.ID);
            if (index==-1) {
                return false;
            }
            products.RemoveAt(index);
            products.Add(item);
            return true;

        }
    }
}

到此,Model层就构建好了。

5)下面,我们要构建Controller层
在此之前,先说一下Http中几种请求类型,如下

    get  类型  用于从服务器端获取数据,且不应该对服务器端有任何操作和影响

    post 类型  用于发送数据到服务器端,创建一条新的数据,对服务器端产生影响

    put 类型  用于向服务器端更新一条数据,对服务器端产生影响 (也可创建一条新的数据但不推荐这样用)

    delete 类型 用于删除一条数据,对服务器端产生影响

四种请求类型刚好可对应于对数据的 查询,添加,修改,删除
接下来,我们将要建立一个ProductController.cs控制器类,其中的方法都是以“Get Post Put Delete”中的任一一个开头的,这样的开头使得Get类型的请求发送给以Get开头的方法去处理,Post类型的请求交给Post开头的方法去处理,Put和Delete同理。

而以Get开头的方法有好几个也是可以的,此时如何区分到底交给哪个方法执行呢?这就取决于Get开头的方法们的传入参数了

构建Controller层,在Controllers文件夹中建立一个ProductController.cs控制器类,如下:

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

namespace demoApi.Controllers
{
    public class ProductController: ApiController
    {
        static readonly IProductRepository repository = new ProductRepository();

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

        //GET: /api/product/id
        public Product GetProduct(int id)
        {
            Product item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return item;
        }
        //POST: api/product
        public HttpResponseMessage PostProct(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);
        }

    }
}

使该类继承于ApiController类,在其中实现处理各种Get,Post,Put,Delete类型Http请求的方法。

每一个方法前都有一句注释,标识了该方法的针对的请求的类型(取决于方法的开头),以及要请求到该方法,需要使用的url。
这里写图片描述

6)最后,我们来构建View视图层,我们更改Views文件夹中的Home文件夹下的Index.cshtml文件,这个文件是项目启动页,如下:

<div id="body">

    <section>
        <h2>添加记录</h2>
        Name:<input id="name" type="text" /><br />
        Department:<input id="category" type="text" />
        Salary:<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 />
        Department:<input id="category2" type="text" />
        Salary:<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 src="~/Scripts/jquery-1.10.2.js"></script>
<script>
        //用于保存用户输入数据
        var Product = {
            create: function () {
                Id: "";
                Name: "";
                Category: "";
                Price: ""; 
                return Product;
            }
        }


        $("#addItem").click(function () {
            var newProduct = Product.create();
            newProduct.Name = $("#name").val();
            newProduct.Category = $("#category").val();
            newProduct.Price = $("#price").val();

            $.ajax({
                url: "/api/Product",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(newProduct),
                success: function () {

                    alert("添加成功!");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                    alert("请求失败,消息:" + textStatus + "  " + errorThrown);
                }
            });
        });


        $("#showItem").click(function () {
            var inputId = $("#id2").val();
            $("#name2").val("");
            $("#category2").val("");
            $("#price2").val("");
            $.ajax({
                url: "/api/Product/" + 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);
                }
            });
        });


        $("#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/Product/" + inputId,
                type: "PUT",
                data: JSON.stringify(newProduct),
                contentType: "application/json; charset=urf-8",
                success: function () {
                    alert("修改成功! ");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("请求失败,消息:" + textStatus + "  " + errorThrown);
                }
            });
        });


        $("#removeItem").click(function () {
            var inputId = $("#id2").val();
            $.ajax({
                url: "/api/Product/" + inputId,
                type: "DELETE",
                contentType: "application/json; charset=uft-8",
                success: function (data) {

                        alert("Id为 " + inputId + " 的记录删除成功!");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("请求失败,消息:" + textStatus + "  " + errorThrown);
                }
            });
        });
</script>

这里,WebApi的一个简单的增删改查项目就完成了,选择执行项目即可测试

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值