1.前言

前端与后端的联系更多是通过API接口对接,API文档变成了前后端开发人员联系的纽带,开始变得越来越重要,而Swagger就是一款让你更好的书写规范API文档的框架。在Ocelot Swagger项目示例中,通过APIGateway项目路由配置网关、上下游服务Swagger。对解决方案中的示例APIServiceA、APIServiceB项目Get方法进行配置,文件配置具体代码如下:

{
  "Routes": [
    {
      //下游服务地址
      "DownstreamPathTemplate": "/swagger/v1/swagger.json",
      //传输协议
      "DownstreamScheme": "http",
      //下游主机跟端口号(数组)
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ],
      //上游服务地址
      "UpstreamPathTemplate": "/a/swagger.json",
      //上游服务Http端口号(数组)
      "UpstreamHttpMethod": [ "Get", "POST" ]
    },
    {
      "DownstreamPathTemplate": "/swagger/v1/swagger.json",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9002
        }
      ],
      "UpstreamPathTemplate": "/b/swagger.json",
      "UpstreamHttpMethod": [ "Get", "POST" ]
    },
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ],
      "UpstreamPathTemplate": "/a",
      "UpstreamHttpMethod": [ "Get" ]

    },
    {
      "DownstreamPathTemplate": "/api/values",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9002
        }
      ],
      "UpstreamPathTemplate": "/b",
      "UpstreamHttpMethod": [ "Get" ]

    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}

2.项目演示

2.1APIGateway项目

添加Ocelot、Swagger服务注入:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:9000")
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config
                .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                .AddJsonFile("ocelot.json")
                .AddEnvironmentVariables();
        })
        .ConfigureServices(s =>
        {
            //添加Ocelot服务;
            s.AddOcelot();
            s.AddMvc();
            //添加Swagger服务;
            s.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "GW", Version = "v1" });
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "APIGateway.xml");
                c.IncludeXmlComments(xmlPath);
            });
        })
        .Configure(a =>
        {
            //使用Swagger
            a.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/a/swagger.json", "APIServiceA");
                c.SwaggerEndpoint("/b/swagger.json", "APIServiceB");
            });

            //使用Ocelot;
            a.UseOcelot().Wait();
        })
        .Build();

2.2APIServiceA项目

Startup添加Swagger服务注入:
ConfigureServices:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "APIServiceA", Version = "v1" });
    var basePath = PlatformServices.Default.Application.ApplicationBasePath;
    var xmlPath = Path.Combine(basePath, "APIServiceA.xml");
    c.IncludeXmlComments(xmlPath);
});
Configure:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIServiceA");
});

添加一个Get方法,对应APIGateway项目的路由上下游配置,具体代码如下:

/// <summary>
/// Values controller.
/// </summary>
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    /// <summary>
    /// Get values.
    /// </summary>
    /// <returns>The get.</returns>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

2.3APIServiceB项目

Startup添加Swagger服务注入:
ConfigureServices:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "APIServiceB", Version = "v1" });
    var basePath = PlatformServices.Default.Application.ApplicationBasePath;
    var xmlPath = Path.Combine(basePath, "APIServiceB.xml");
    c.IncludeXmlComments(xmlPath);
});

Configure:

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIServiceB");
});

添加一个Get方法,对应APIGateway项目的路由上下游配置,具体代码如下:

/// <summary>
/// Values controller.
/// </summary>
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    /// <summary>
    /// Get values.
    /// </summary>
    /// <returns>The get.</returns>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value3", "value4" };
    }
}

2.4项目运行

注:如果想把Swagger注释警告提示取消,可以在对应项目文件.csproj的PropertyGroup节点上加入<NoWarn>$(NoWarn);1591</NoWarn>这一行代码。
输入dotnet run --project 项目路径\项目文件.csproj把三个项目启动起来,通过在浏览器分别打开APIServiceA与APIServiceB两个站点上游服务Swagger地址,会看到如下信息:
APIServiceA:
(7)ASP.NET Core3.1 Ocelot Swagger-LMLPHP
APIServiceB:
(7)ASP.NET Core3.1 Ocelot Swagger-LMLPHP
通过网关的路由配置,把Swagger集成到Ocelot中,统一入口管理,通过网关入口我们就能打开不同下游服务的Swagger。

11-20 20:54