Aspnet Core 对 Resetful API版本的支持

在实际项目过程中API往往会收到迭代的影响,同时具备多个版本,因此resetful接口的版本话是非常重要的。

其实官方就提供了很好的支持,微软爸爸在nuget提供了Microsoft.AspNetCore.Mvc.Versioning 2.3.0

该包还具有很多其他的功能,具体细节请移步官方的github

废话不多,直接上步骤

  1. Nuget安装 Microsoft.AspNetCore.Mvc.Versioning.
  2. startup.cs中做如下配置
    public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
            }
    

      

  3. 加入Controller内的配置

    using Microsoft.AspNetCore.Mvc.Versioning;
    namespace Product.CommandService.Controllers.Product.V1
    {
      [ApiVersion("1.0")]
      [Produces("application/json")]
      [Route("api/Product")]
      public class ProductController : Controller
      {
      }
    }
    
    namespace Product.CommandService.Controllers.Product.V2
    {
      [ApiVersion("2.0")]
      [Produces("application/json")]
      [Route("api/Product")]
      public class ProductController : Controller
      {
      }
    }
    

      

  4. 如果你不希望有些接口使用API Version

    [ApiVersionNeutral]
    [Route("api/optout")]
    public class OptOutControler : Controller
    {
        [HttpGet]
        public string Get() => HttpContext.GetRequestedApiVersion().ToString();
    }
    

      


  5. 之后客户端访问的时候都需要在头部加入api-version,如nodejs实例代码
    var http = require("http");
    
    var options = {
      "method": "GET",
      "hostname": [
        "localhost"
      ],
      "port": "5000",
      "path": [
        "ioc",
        "showmodule"
      ],
      "headers": {
        "api-version": "1.0",
        "Cache-Control": "no-cache",
        "Postman-Token": "2286a575-559d-4789-8056-eb26223f6fa4"
      }
    };
    
    var req = http.request(options, function (res) {
      var chunks = [];
    
      res.on("data", function (chunk) {
        chunks.push(chunk);
      });
    
      res.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
      });
    });
    
    req.end();

 

posted @ 2018-10-05 19:01  linkanyway  阅读(287)  评论(0编辑  收藏  举报