【问题标题】:Configuring Swagger with values from Iconfiguration object使用来自 Iconfiguration 对象的值配置 Swagger
【发布时间】:2019-04-20 14:04:18
【问题描述】:

我正在尝试在 startup.cs 中配置 swagger。如果我给它所需的值“硬编码”如下in ASP.NET Core : 2.2

    services.AddSwaggerGen(c =>
    {
      c.SwaggerDoc("V1", new Info { Title = "MY.API", Version ="v1" });
    });

    app.UseSwagger();
    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MY.API V1");
    });

但如果我从 asp.net 核心提供的“IConfiguration”对象中设置所有上述硬编码值,那么它就会停止工作,

services.AddSwaggerGen(c =>
{
   c.SwaggerDoc(this.Configuration.GetSection("AppSetting") 
   ["APIName"], new Info { Title = "My.API", Version = "v1" });
}); 

操作系统:Windows 10 专业版

【问题讨论】:

    标签: c# asp.net-core configuration swagger-ui


    【解决方案1】:

    这应该是评论,但我没有足够的业力。

    首先请向我们展示您的 appsettings.json。 第二次检查该行是否实际返回正确的值,而不是 null 或空字符串(只需将其放在本地 var 中):

    this.Configuration.GetSection("AppSetting")["APIName"]
    

    编辑: 名称字段似乎区分大小写。确保在 UseSwaggerUI 中也使用配置中的值:

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint($"/swagger/{this.Configuration.GetSection("AppSetting")["APIName"]}/swagger.json", "MY.API V1");
    });
    

    【讨论】:

    • Artur :我做了调试,是的,它返回了相同的字符串,在这里作为硬编码传递
    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 2017-05-13
    • 2016-04-16
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多