zoukankan      html  css  js  c++  java
  • ASP.NET Core Web API初探

    本章将和大家分享ASP.NET Core中的Web API。

    一、RESTful架构风格

    REST(Representational State Transfer)表现层的状态转化,是一个接口的设计风格。是Web服务的一种新的架构风格(一种思想)。

    资源:万物看成资源。

    使用POST,DELETE,PUT和GET四种请求方式分别对指定的URL资源进行增删改查操作,RESTful是通过URI实现对资源的管理及访问,具有扩展性强、结构清晰的特点。

    URI:统一资源标识符,资源对应的唯一地址。

    统一接口:CRUD增删改查,跟HTTP Method对应

    REST架构的主要原则:

      1、对网络上所有的资源都有一个资源标志符。

      2、对资源的操作不会改变标识符。

      3、同一资源有多种表现形式(xml、json)。

      4、所有操作都是无状态的(Stateless)。

    符合上述REST原则的架构方式称为RESTful

    无状态

      基于Http协议,(登陆系统--查询工资--计算税收,有状态)

      无状态的直接一个地址,就能拿到工资,就能得到税收

    关于RESTful更多资料可参考博文:https://blog.csdn.net/x541211190/article/details/81141459

    二、Web API

    WebApi:RESTful架构风格,http协议 无状态 标准化操作  更轻量级,尤其是json,适合移动端。

    Web API和MVC差别:

      专人做专事,它们的管道模式是不一样的。

      Web API中是没有生成页面这套东西的,它不需要去找视图那些东西,它也不存在去弄session之类的,Web API是专门提供数据的,比起MVC来讲Web API更轻量级。

      Web API严格遵守了RESTful架构风格。

    接下来我们来看下代码部分:

    1、Web API项目创建(使用VS2019)

    创建成功后如下所示:

    接下来我们添加一个名为Users的API控制器:

    添加完成后我们来看下API控制器的结构:

    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
    
    namespace MyWebAPI.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class UsersController : ControllerBase
        {
            // GET: api/<UsersController>
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET api/<UsersController>/5
            [HttpGet("{id}")]
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/<UsersController>
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }
    
            // PUT api/<UsersController>/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE api/<UsersController>/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
    }

    可以看出API控制器继承了ControllerBase基类,标记了 [ApiController] Api控制器特性和 [Route("api/[controller]")] 路由特性,

    以及不同类型的Action方法也分别标记了不同的特性,分别为:HttpGet、HttpPost、HttpPut、HttpDelete特性,这四个特性分别对应着查、增、改、删四个HTTP Method方法。

    2、Web API路由

    Web API路由规则如下:

      1、请求进来时,会经过路由匹配找到合适的控制器。

      2、那怎么找Action呢?

        1)根据HttpMethod找方法,用方法名字开头(即使用Post、Delete、Put、Get这四个开头),Get开头就是对应Get请求。(该点在.NET Framework框架中适用)

        2)如果不是使用Post、Delete、Put、Get这四个开头,也可以使用HttpGet、HttpPost、HttpPut、HttpDelete这四大特性。

        3)按照参数找最吻合

        4)在.NET Core路由中会优先匹配标记了HttpGet、HttpPost、HttpPut、HttpDelete这四大特性的Action,在没有匹配到的情况下才会去匹配别的Action,而且该Action可以不使用Post、Delete、Put、Get这四个开头。

    熟悉MVC的人一开始可能会对这个规则很不习惯,在MVC中我们是通过控制器和Action定位到具体操作的。但是为什么在Web API中却不是这样的?

    这是因为我们的Web API是严格遵循RESTful风格的,在RESTful风格中只有资源(万物皆资源)和增删改查操作,这里的资源可以把它看成我们的控制器,

    那有了资源之后我们还需要去传递具体的方法或者说Action吗?不需要,这是因为我们的RESTful风格在设计的时候就已经将我们的增删改查操作对应到具体的HttpMethod方法(即Post、Delete、Put、Get这四大类型)。

    下面我们通过具体的例子来看下Web API的路由规则:

    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
    
    namespace MyWebAPI.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            [HttpGet("{id:int}/Type/{typeId:int=666}")] //访问路径:http://localhost:5000/api/values/1/type/666
            //[HttpGet("Get")] //访问路径:http://localhost:5000/api/values/get?id=1&typeId=666
            //[Route("/api/[controller]/{id:int}/Type/{typeId:int}")] //访问路径:http://localhost:5000/api/values/1/type/666 (不推荐)
            public string Get(int id, int typeId)
            {
                return $"value-Type {id} {typeId}";
            }
    
            //[HttpGet("{name}")]
            [Route("api/[controller]/{name}")]
            //路由模板不以“/”或“~/”开头则Action特性路由会和控制器特性路由叠加(合并)
            //访问路径:http://localhost:5000/api/values/api/values/abc
            public string OverlyingGet(string name)
            {
                return $"OverlyingGet {name}";
            }
    
            //同是HttpGet请求时别的Action没有标记HttpGet情况下则会匹配该Action
            public IEnumerable<string> Test()
            {
                return new string[] { "Test1", "Test2" };
            }
    
            // GET: api/<ValuesController>
            [HttpGet] //同是HttpGet请求时优先匹配带有HttpGet特性的
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET api/<ValuesController>/5
            [HttpGet("{id:int?}")]
            public string Get(int id)
            {
                return $"value-{id}";
            }
    
            // POST api/<ValuesController>
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }
    
            // PUT api/<ValuesController>/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE api/<ValuesController>/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
    }

    PS:路由模板不以“/”或“~/”开头则Action特性路由会和控制器特性路由叠加(合并)。

    使用.NET Core CLI来启动下项目:

    可以看出项目启动成功了,接下来我们使用浏览器来模拟HttpGet请求:

    首先我们来看下采用MVC传统路由的方式访问有什么效果:

    可以看到访问失败了,这是因为默认情况下WebApi的路由规则是RESTful风格的,接下来我们来看下正确的访问方式:

    至此,我们已经给大家show完一波RESTful风格的路由规则了,那有人可能会问能不能改成传统的MVC路由规则呢?接下来我们就来演示一下:

    首先要将控制器上面的[Route("api/[controller]")]和[ApiController]特性注释掉(PS:一旦标记了[ApiController]特性就必须要标记[Route("...")]特性)

    然后修改Startup.cs文件,增加全局路由模板:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseRouting();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            //endpoints.MapControllers(); //框架默认生成的
            endpoints.MapControllerRoute(
                name: "defaultWithAreas",
                pattern: "api/{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "api/{controller=Home}/{action=Index}/{id?}");
        });
    }

    最后重新通过浏览器来访问下:

    全局路由和特性路由可以共存,优先匹配特性路由

    可以看出,此时采用传统路由规则访问就能够成功了。

    更多关于.NET Core路由的参考资料,如下:

    微软官网关于ASP.NET Core 中的路由(包括路由约束):https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/routing?view=aspnetcore-3.1

    特性路由合并:https://blog.csdn.net/sinolover/article/details/104329265/

    Web API路由:https://blog.csdn.net/qq_34759481/article/details/85018684

    关于路由的就介绍到这里了。

    3、使用ajax请求Web API(PS:此处没有使用RESTful风格,而是采用传统的路由风格。)

    为了演示我们额外建了一个MVC的项目,首先我们来看下MVC的前端代码部分:

    @{
        ViewData["Title"] = "Home Index";
        Layout = null;
    }
    
    <div class="text-center">
        <form id="frmUser">
            <p>
                用户Id:<input type="text" id="txtId" name="UserID" />
            </p>
            <p>
                <input type="button" id="btnGet1" value="Get1" />
            </p>
            <p>
                <input type="button" id="btnPost1" value="Post1" />
            </p>
            <p>
                <input type="button" id="btnPut1" value="Put1" />
            </p>
            <p>
                <input type="button" id="btnDelete1" value="Delete1" />
            </p>
        </form>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script>
            var user = { UserID: "10002", UserName: "TianYa", UserEmail: "12306@qq.com" };
            var dirName = "http://localhost:5001";
            $("#btnGet1").on("click", function () {
                $.ajax({
                    url: dirName + "/api/users/GetUserByID",
                    type: "get",
                    data: $("#frmUser").serialize(),
                    success: function (data) {
                        console.log(data);
                    },
                    datatype: "json"
                });
            });
    
            $("#btnPost1").on("click", function () {
                $.ajax({
                    url: dirName + "/api/users/PostUser",
                    type: "post",
                    data: user,
                    success: function (data) {
                        console.log(data);
                    },
                    datatype: "json"
                });
            });
    
            $("#btnPut1").on("click", function () {
                $.ajax({
                    url: dirName + "/api/users/PutUser",
                    type: "put",
                    data: $("#frmUser").serialize(),
                    success: function (data) {
                        console.log(data);
                    },
                    datatype: "json"
                });
            });
    
            $("#btnDelete1").on("click", function () {
                $.ajax({
                    url: dirName + "/api/users/DeleteUser",
                    type: "delete",
                    data: { "userID": $("#txtId").val() },
                    success: function (data) {
                        console.log(data);
                    },
                    datatype: "json"
                });
            });
        </script>
    </div>

    接着我们来看下Web API的相关代码:

    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    using TianYa.Interface;
    using TianYa.Model;
    
    namespace MyWebAPI.Controllers
    {
        //[Route("api/[controller]")]
        //[ApiController]
        public class UsersController : ControllerBase
        {
            private readonly IUserService _userService;
            public UsersController(IUserService userService)
            {
                _userService = userService;
            }
    
            [HttpGet]
            public Users GetUserByID(int userID)
            {
                return _userService.GetModel(userID);
            }
    
            [HttpPost]
            public Users PostUser(Users user)
            {
                return _userService.GetModel(user.UserID);
            }
    
            [HttpPut]
            public Users PutUser(Users user)
            {
                return _userService.GetModel(user.UserID);
            }
    
            [HttpDelete]
            public Users DeleteUser(int userID)
            {
                return _userService.GetModel(userID);
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace TianYa.Model
    {
        /// <summary>
        /// 用户
        /// </summary>
        public class Users
        {
            public int UserID { get; set; }
            public string UserName { get; set; }
            public string UserEmail { get; set; }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    using TianYa.Model;
    using TianYa.Interface;
    
    namespace TianYa.Service
    {
        /// <summary>
        /// 用户服务层
        /// </summary>
        public class UserService : IUserService
        {
            private List<Users> _listUsers = new List<Users>();
            public UserService()
            {
                _listUsers.Add(new Users
                {
                    UserID = 10000,
                    UserName = "张三",
                    UserEmail = "zhangsan@qq.com"
                });
                _listUsers.Add(new Users
                {
                    UserID = 10001,
                    UserName = "李四",
                    UserEmail = "lisi@qq.com"
                });
                _listUsers.Add(new Users
                {
                    UserID = 10002,
                    UserName = "王五",
                    UserEmail = "wangwu@qq.com"
                });
                _listUsers.Add(new Users
                {
                    UserID = 10003,
                    UserName = "赵六",
                    UserEmail = "zhaoliu@qq.com"
                });
            }
    
            public Users GetModel(int userId)
            {
                return _listUsers.FirstOrDefault(m => m.UserID == userId) ?? _listUsers[0];
            }
        }
    }

    然后使用.NET Core CLI来分别启动MVC项目和Web API项目,启动成功后我们来访问下:

    从运行结果中可以发现:

    1、在Web API的Action方法中返回的是Users类型,但是响应到前端的时候Web API会帮我们自动转换成指定的类型(例如:Json或XML)。

    2、响应到前端的Json数据的格式默认采用的是驼峰命名法。

    那怎么才能使响应到前端的Json数据保留原来的格式呢?

    首先需要先引用 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包:

    然后修改Startup.cs文件,如下所示:

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    using TianYa.Interface;
    using TianYa.Service;
    
    namespace MyWebAPI
    {
        public class Startup
        {
            private readonly string _myCorsPolicy = "MyCorsPolicy";
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers().AddNewtonsoftJson(options =>
                {
                    // 忽略循环引用
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    // 不使用驼峰
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    // 设置时间格式
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    // 如字段为null值,该字段不会返回到前端
                    // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                });
                services.AddCors(options => //设置跨域策略
                    options.AddPolicy(_myCorsPolicy, builder =>
                     {
                         builder
                            .AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                     })
                );
                services.AddTransient<IUserService, UserService>(); //依赖注入
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
                app.UseAuthorization();
                app.UseCors(_myCorsPolicy);
                app.UseEndpoints(endpoints =>
                {
                    //endpoints.MapControllers(); //框架默认生成的
                    endpoints.MapControllerRoute(
                                name: "defaultWithAreas",
                                pattern: "api/{area:exists}/{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "api/{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

    设置完成,重新启动成功后,我们再来访问下:

    从运行结果可以看出此时返回到前端的Json数据保留了原来的格式。

    更多关于ajax请求Web API的可参考博文:

      https://blog.csdn.net/weixin_43537631/article/details/110563779

    更多关于Web API相关知识的可参考微软官网:

      https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio

      https://docs.microsoft.com/zh-cn/aspnet/core/web-api/?view=aspnetcore-5.0

    至此本文就全部介绍完了,如果觉得对您有所启发请记得点个赞哦!!!

    Demo源码:

    链接:https://pan.baidu.com/s/1cJPAVpKao3raiS_hTH66bw 
    提取码:s5ft

    此文由博主精心撰写转载请保留此原文链接:https://www.cnblogs.com/xyh9039/p/14163991.html

    版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

  • 相关阅读:
    python+selenium环境搭建以及遇到的坑
    (二)第一个测试用例
    (一)TestNG介绍与安装
    Appium详解server capabilities
    Mac安装MySQL数据库
    POI 设置单元格样式
    JAVA_HOME环境变量失效的解决办法
    svn linux 命令
    StringUtils工具类的常用方法
    ArrayUtils 方法
  • 原文地址:https://www.cnblogs.com/xyh9039/p/14163991.html
Copyright © 2011-2022 走看看