ASP.NET WebAPI 01-Demo

WebAPI作为构建RESTful的平台出来有段时间了,加上最近也在用,所以想把自己的心得记录下来。我就以一个简单的增删查改作为开篇。

准备

实体类(Figure)的定义。

    public class Figure
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

  

再定义一静态类FigureManager用于存储要操作的Figure集合。

public static class FigureManager
    {
        static List<Figure> figures;
        static FigureManager()
        {
            figures = new List<Figure>();
            figures.Add(new Figure("Eddard", "Stack"));
            figures.Add(new Figure("Robb", "Stack"));
            figures.Add(new Figure("Sansa", "Stack"));
            figures.Add(new Figure("Arya", "Stack"));
            figures.Add(new Figure("Bran", "Stack"));
            figures.Add(new Figure("Rickon", "Stack"));
            figures.Add(new Figure("Jon", "Snow"));
        }
        public static List<Figure> Figures
        {
            get { return figures; }
        }
    }

  

CRUD

一般情况下我们操作的可能就是增删查改,所以demo中我就采用这几种基本的操作(因为修改与新增动作在前端得到的效果相似,所以就暂时没有写修改的例子)。

查询所有(GET)

public IEnumerable<Figure> GetAll()

这个方法我将FigureManager.Figures返回作为结果。

通过FirstName进行查询(GET)

在这里我采用了两种传参方式:QueryString与Route

QueryString

public Figure GetByQueryString(string firstName)

url: http://localhost:4296/api/Figure/GetByQueryString?firstName=Bran

Route:

[Route("api/Figure/GetByRoute/{firstName}")]

public Figure GetByRoute(string firstName)

url: http://localhost:4296/api/Figure/GetByRoute/Bran

新增(POST)

对于新增,由于Figure类的属性只有两个,所以demo中采用的四种方法(为了方便查看每个方法的都将FigureManager.Figures作为返回值):

  1. 直接获取FirstName,LastName

    public IEnumerable<Figure> PostByUrl(string firstName, string lastName)

    url: http://localhost:4296/api/Figure/PostByUrl?FirstName=Catelyn&LastName=Tully

     

  2. 通过QueryString进行Model绑定

    public IEnumerable<Figure> PostByUrlModel(Figure figure)

    url:http://localhost:4296/api/Figure/PostByUrlModel?FirstName=Catelyn&LastName=Tully

     

    通过Route进行Model绑定

    [Route("api/Figure/PostByRouteModel/{FirstName}/{LastName}")]

    public IEnumerable<Figure> PostByRouteModel(Figure figure)

    url: http://localhost:4296/api/Figure/PostByRouteModel/Catelyn/Tully

     

  3. 通过Body传递Model

    public IEnumerable<Figure> PostByBody([FromBody] Figure figure)

    url: http://localhost:4296/api/Figure/PostByBody

    body:

    {

    "FirstName":"Catelyn",

    "LastName":"Tully"

    }

     

删除(DELETE)

因为Http提供了DELETE请求方式,所以就直接使用Delete请求进行删除操作:

public IEnumerable<Figure> Delete(string firstName)

url: http://localhost:4296/api/Figure/Delete?FirstName=Catelyn

源码

GitHub: https://github.com/BarlowDu/WebAPI

原文地址:https://www.cnblogs.com/gangtianci/p/4759042.html