【问题标题】:Swagger response description not shown未显示 Swagger 响应描述
【发布时间】:2020-09-15 15:40:38
【问题描述】:

我目前正在尝试在 Swagger UI 中显示特定响应的描述,但似乎没有真正涵盖所有方面的文档,以及我从 Get started with Swashbuckle and ASP.NET Coredon 尝试过的所有示例不能在 .NET Core 3.1 中工作...

        /// <summary>
        /// Test route...
        /// </summary>
        /// <returns></returns>
        /// <response code="200">This is a test</response>
        [HttpGet]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        public IActionResult Get()
        {
            return Ok("Hello World");
        }

我的 .csproj 还包含以下内容:

  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
  </PropertyGroup>

Swagger UI 最终看起来像这样(如您所见,“Descriptipn”列不包含它可能应该包含的“这是一个测试”文本)。我错过了什么吗?

我还添加了[SwaggerResponse(StatusCodes.Status200OK, ...)],但没有任何变化。

【问题讨论】:

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


【解决方案1】:

事实证明,[SwaggerResponse] 工作正常,但在此之前,我需要在我的启动中“启用注释”...

    services.AddSwaggerGen(config =>
    {
        config.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "Some API",
            Version = "v1"
        });

        config.EnableAnnotations();
    });

【讨论】:

    【解决方案2】:

    在您的项目属性中,您应该检查在刀片 Build 下找到的 Output XML documentation file。然后在您的startup 文件中:

    services.AddSwaggerGen(c =>
    {
        //rest of your code
    
        //i'm using the default path generated, but you can adjust it as you want
        var XMLPath = AppDomain.CurrentDomain.BaseDirectory + nameof(MyNamespace) + ".xml";
        if (File.Exists(XMLPath))
        {
            c.IncludeXmlComments(XMLPath);
        }
    });
    

    如果这仍然不起作用,请检查 xml 文件是否出现在 bin 文件夹中。如果不检查 Visual Studio 中的属性并将Copy to output directory 调整为CopyCopy if newer

    【讨论】:

      【解决方案3】:

      根据official docs,它是通过 XML 注释完成的:

      <response code="201">This is a test</response>
      

      cmets 需要链接到 Swagger

      builder.Services.AddSwaggerGen(options =>
      {
          // using System.Reflection;
          var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
          options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
      });
      

      【讨论】:

        猜你喜欢
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-25
        • 2017-11-16
        相关资源
        最近更新 更多