• 创建支持CRUD(增删改查)操作的Web API(二)


    一:准备工作

       

      你可以直接下载源码查看

         Download the completed project.
         下载完整的项目

       CRUD是指“创建(C)、读取(R)、更新(U)和删除(D)”,它们是四个基本的数据库操作。许多HTTP服务也会通过REST或类REST的API模拟CRUD操作。

      在本教程中,我们将建立一个十分简单的Web API来管理一列产品。

    每个产品包含一个name(名称)、price(价格)和category(分类)(如,“toys(玩具)”、“hardware(硬件)”等),还有一个产品的ID。

    表2-1. Products API 具有下面几个的HTTP方法

    Action
    动作
    HTTP method
    HTTP方法
    Relative URI
    相对URI
    Get a list of all products
    获取全部产品列表
    GET /api/products
    Get a product by ID
    通过ID获取一个产品
    GET /api/products/id
    Get a product by category
    通过分类获取产品
    GET /api/products?category=category
    Create a new product
    创建一个新产品
    POST /api/products
    Update a product
    更新一个产品
    PUT /api/products/id
    Delete a product
    删除一个产品
    DELETE /api/products/id

      

    注意,有些URI在路径中包含了产品ID。例如,要得到ID为28的产品,客户端要发送一个http://hostname/api/products/28的GET请求。

    二:方法

     

     下面来说下增删改查CRUD的四种方法

      1.GET接收指定URI上的资源表达式。GET在服务器上应当没有副效应。(区分URI URL URN)

      2.PUT更新指定URI上的资源。如果服务器允许客户端指定新URI,PUT也可以用于在指定URI上创建新资源。对于本教程,API将不支持通过PUT的创建。

      3.POST创建新资源。服务器为新对象分配URI,并把这个URI作为响应消息的一部分加以返回。

      4.DELETE删除指定URI上的资源。

    三:创建一个新的WEBAPI项目 

     启动VS 2013,并在“开始页”选择“新项目”。或从“文件”菜单选择“新建”,然后选择“项目”。

    在“模板”面板中选择“已安装模板”,并展开“Visual C#”节点。选择该节点下的“Web”。在项目模板列表中选择“ASP.NET MVC 4 Web应用程序”。将此项目命名为“ProductStore”,点击“OK”

      

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

      

     1.添加模型

        模型是表示你应用程序中数据的一种对象。在ASP.NET Web API中,你可以使用强类型的CRL(公共语言运行时)对象作为模型,而它们将被自动化地序列化成用于客户端的XML或JSON

      对于这个ProductStore API,其数据由产品组成,因此,我们将创建一个名为Product的新类

      如果“解决方案资源管理器”此时尚不可见,点击“视图”菜单,并选择“解决方案资源管理器”。在“解决方案资源管理器”中,右击“Models”文件夹。从上下菜单中选择“添加”,然后选择“类”。将这个类命名为“Product”(如图)

      

      将以下属性添加到这个Product类。

      

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ProductStore.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
        }
    }

      2.添加存储库

        我们需要存储产品集合。将这个集合与我们的服务实现分开是一种好的思想。这样,我们可以修改后台存储而不必重写服务类。这种设计类型称为存储库模式。首先从定义存储库的泛型接口开始

      在“解决方案资源管理器”中,右击“Models”文件夹。选择“添加”,然后选择“新项”

        

      

      在“模板”面板中,选择“已安装模板”,并展开“C#”节点,选择“代码”。在代码模板列表中选择“接口”。将此接口命名为“IProductRepository”

      

      添加以下实现:

      

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ProductStore.Models
    {
        interface IProductRepository
        {
            IEnumerable<Product> GetAll();
            Product Get(int id);
            Product Add(Product item);
            void Remove(int id);
            bool Update(Product item);
        }
    }

      现在,把另一个类添加到Models文件夹,名称为“ProductRepository”。这个类将实现这个IProductRespository接口。添加以下实现

      

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace ProductStore.Models
    {
        //实现接口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 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; 
            }
        }
    }

      

      该存储库在本地内存中保持了一个产品列表。对一个教程而言这就行了,但在一个真实应用程序中,你要在外部存储这些数据,可以是一个数据库,或是云存储库。这种存储库模式会使今后对这个实现的修改很容易

      

      3.添加Web API控制器

        如果你曾使用过ASP.NET MVC,对控制器是熟悉的。在ASP.NET Web API中,控制器是一种处理客户端HTTP请求的类。“新项目”向导在创建项目时,为你创建了两个控制器。要看到它们,可以在“解决方案资源管理  器”中展开Controllers文件夹。

      (1).HomeController一个传统的ASP.NET MVC控制器。它负责对网站的HTML页面进行服务,而与Web API无直接关系。

      (2).ValuesController是一个WebAPI控制器例子。

      继续并删除这个ValuesController,在“解决方案资源管理器”中右击这个文件,并选择“删除”。现在,添加一个新控制器,操作如下:

      在“解决方案资源管理器”中,右击Controllers文件夹。选择“添加”,然后选择“控制器”

      

      在“添加控制器”向导中,将此控制器命名为“ProductsController”。在“模板”下拉列表中选择“空的API控制器”。然后点击“添加”

      

      注意是空api控制器不是空控制器

      “添加控制器”向导将在Controllers文件夹中创建一个名为ProductsController.cs的文件。如果这个文件尚未打开,双击此文件打开它。添加以下的using语句

      

    using ProductStore.Models;

      添加一个保存IProductRepository实例的字段

    using ProductStore.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace ProductStore.Controllers
    {
        public class ProductsController : ApiController
        {
            static readonly IProductRepository repository = new ProductRepository();
    
        }
    }

       4.增删改查方法

        这个ProductStore API      具体代码在Model 文件夹中的ProductRepository类中查看

     

  • 相关阅读:
    TweenLite简单运用
    nodejs 重定向 (redirect + writeHead(Location))
    Nodejs Web模块( readFile 根据请求跳转到响应html )
    Express框架(http服务器 + 路由)
    AI 学习路线
    implicitly_wait()隐式等待
    Python 爬虫基础Selenium
    Selenium2+python自动化15-select下拉框
    python selenium while 循环
    jupyter notebook修改默认路径和浏览器
  • 原文地址:https://www.cnblogs.com/DemoLee/p/4003658.html
Copyright © 2020-2023  润新知