.Net Core微服务入门——Swagger接入

26 篇文章 1 订阅
13 篇文章 1 订阅

.Net Core微服务入门——Swagger接入

一、API接入Swagger

1、引入包:Swashbuckle.AspNetCore

2、修改Startup,在ConfigureServices 中添加 Swagger

public void ConfigureServices(IServiceCollection services)
{
    // 添加Swagger
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
    services.AddControllers();
}

3、修改Startup,在Configure方法里面添加Swagger有关的中间件

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        
        // 添加Swagger有关中间件
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1");
        });

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        //注册 Consul
        this.Configuration.ConsulRegist();
    }

4、启动调试,查看结果

https://localhost:49167/swagger
在这里插入图片描述

Swagger 成功接入,但是我们发现,只显示了接口,却没有显示相关描述信息。
不着急,我们继续!

二、API Swagger添加描述

1、引入包:Microsoft.Extensions.PlatformAbstractions

2、修改Startup,在ConfigureServices中注入xml相关描述

public void ConfigureServices(IServiceCollection services)
{
     // 添加Swagger
     services.AddSwaggerGen(c =>
     {
         c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

         // 获取xml文件名
         var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
         // 获取xml文件路径
         var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
         // 添加控制器层注释,true表示显示控制器注释
         c.IncludeXmlComments(xmlPath, true);
     });

     services.AddControllers();

     //Development、Staging、Production
     //AppSetting.SetAppSetting(Configuration.GetSection("ConnectionStrings"));
     //设置配置
     AppConfiguration.SetConfiguration(Configuration);

     //注入数据库
     var connStr = Configuration.GetConnectionString("SQLServerConnection");
     services.AddDbContext<SqlContext>(builder => builder.UseSqlServer(connStr));

     //注入Mysql数据库
     var connMysqlStr = Configuration.GetConnectionString("MySQLConnection");
     services.AddDbContextPool<MySqlContext>(builder => builder.UseMySql(connMysqlStr, new MySqlServerVersion(new Version(5, 7, 21))));
     //services.AddDbContextPool<MySqlContext>(builder => builder.UseMySql(connMysqlStr, new MySqlServerVersion(new Version(8, 0, 11))));
 }

3、项目右键,选择属性,勾选“XML文档文件”,如下图所示:

在这里插入图片描述
4、选中项目 xxxxx.xml,修改成 如果较新则复制

在这里插入图片描述
为什么要这样设置呢,如果不设置的话,发布时候会出问题,找不到 xml文件

4、启动调试,查看结果

https://localhost:49167/swagger

在这里插入图片描述

API已经接入了swagger,但是我们是不直接访问api,而是访问网关,那网关怎么接入Swagger呢

三、Ocelot添加Swagger

1、引入包:Swashbuckle.AspNetCore

2、修改Startup,在ConfigureServices 中添加 Swagger

public void ConfigureServices(IServiceCollection services)
{
    string consulport = Configuration["consulport"];
    if (!string.IsNullOrWhiteSpace(consulport))
    {
        Configuration["GlobalConfiguration:ServiceDiscoveryProvider:Port"] = consulport;
    }

    services.AddMvc();
    //注入Swagger
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1",
            new OpenApiInfo { Title = "Gateway API", Version = "v1", Description = "# gateway api..." });
    });

    //添加ocelot服务
    //services.AddOcelot();
    //添加ocelot服务
    services.AddOcelot()
        //添加consul支持
        .AddConsul()
        //添加缓存
        .AddCacheManager(x =>
        {
            x.WithDictionaryHandle();
        })
        //添加Polly
        .AddPolly();

}

3、修改Startup,在Configure方法里面添加Swagger有关的中间件

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseSwagger();
     app.UseSwaggerUI(c =>
     {
         //这里要与 UpstreamPathTemplate 相同,支持配置多个
         c.SwaggerEndpoint("/myapi/swagger/v1/swagger.json", "MyAPI V1");
     });

     //设置Ocelot中间件
     app.UseOcelot().Wait();

 }

4、修改ocelot.json,增加Swagger配置

"Routes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/api/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "ServiceName": "MyApi",
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      },
      "FileCacheOptions": {
        "TtlSeconds": 5,
        "Region": "regionname"
      },
      "RateLimitOptions": {
        "ClientWhitelist": [ "SuperClient" ], //白名单
        "EnableRateLimiting": true, //是否开启限流
        "Period": "5s",
        "PeriodTimespan": 2,
        "Limit": 5
      },
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //发生错误的次数
        "DurationOfBreak": 10000, //熔断时间 毫秒
        "TimeoutValue": 5000 //超时时间 毫秒
      }
    },
    {
      //引入swagger
      "DownstreamPathTemplate": "/swagger/v1/swagger.json",
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/myapi/swagger/v1/swagger.json",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "ServiceName": "MyApi",
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      }
    }
 ]

5、调试启动

https://localhost:49171/swagger/index.html

在这里插入图片描述
在这里插入图片描述

完成!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值