【问题标题】:Adding comments to endpoints w/ Swagger使用 Swagger 向端点添加注释
【发布时间】:2020-01-10 19:41:41
【问题描述】:

我正在为我的 API 使用 Swagger / Swashbuckle。我希望 Swagger UI 显示方法描述。在他们的documents 中写道:


2 - 配置 Swashbuckle 以将文件中的 XML cmets 合并到生成的 Swagger JSON 中:

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

     var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
     c.IncludeXmlComments(filePath);
}

有人可以解释一下吗?我应该用这段代码做什么?我是否将其复制并粘贴到某处?如果有,在哪里?

(.NET 框架 4.7)

编辑:

下面 Jawad 的回答让我找到了解决方案。在原始的 SwaggerConfig.cs 文件中,有这样的:

// If you annotate Controllers and API Types with
// Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate
// those comments into the generated docs and UI. You can enable this by providing the path to one or
// more Xml comment files.
//
//c.IncludeXmlComments(GetXmlCommentsPath());

我不清楚如何更改最后一行以添加我的 XML 文件。这有效:

c.IncludeXmlComments(Path.Combine(System.AppContext.BaseDirectory, "bin\\KGC.API.xml"));

我还必须添加using System.IO

【问题讨论】:

  • App_Start 下有 SwaggerConfig.cs 文件吗?
  • 是的。我一直在研究它并试图弄清楚在哪里/如何将这段代码添加到它
  • wmpratt.com/swagger-and-asp-net-web-api-part-1 -> 也可以将其用于配置的其他方面 :)
  • 看起来这段代码将在 ConfigureServices 方法的 Startup 中进行

标签: c# .net api swagger


【解决方案1】:

我的做法是更新 SwaggerConfig.cs 文件..

    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration
            .EnableSwagger("docs/{apiVersion}", c =>
            {
                c.SingleApiVersion("v1", "Title Of API");
                c.Schemes(new List<string> { "http", "https" });
                c.UseFullTypeNameInSchemaIds();
                c.IncludeXmlComments(Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml"));
            });
    }

上面代码的最后一行启用了 XML 注释标记。

你必须做的另一件事是,

  1. 转到项目的属性(不是解决方案)
  2. 构建/输出 -> 添加 XML 文档文件的路径。

供参考,this 很有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2022-01-02
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多