如何在Swashbuckle中包含类和属性描述,使用OWIN为Web Api 2生成Swagger文档?

问题描述 投票:8回答:2

在你想到它之前,this是不一样的。

我认为这应该是非常自我解释的。我想在Swagger文档中包含类描述。我的Swagger配置看起来像这样:

config.EnableSwagger(c =>
{
    c.SingleApiVersion("v1", "My Api Name");
    c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
    c.IncludeXmlComments(GetXmlCommentsPath());

}).EnableSwaggerUi(c => { });

MyAwesomeController看起来像这样:

/// <summary>
/// Controller description (is included by Swashbuckle)
/// </summary>
public class MyAwesomeController : ApiController
{
    /// <summary>
    /// Method description (is included by Swashbuckle)
    /// </summary>
    public IHttpActionResult Get()
    {
        return Ok("hello... from the other side");
    }

    public IHttpActionResult Post([FromBody]MyAwesomeModel model)
    {
        return Ok("hello... from the other side");
    }
}

而我的MyAwesomeModel看起来像这样:

/// <summary>
/// **I would like this to be included in the Swagger description of the parameter**
/// </summary>
public class MyAwesomeModel
{
    /// <summary>
    /// **I would like this to be included in the Swagger description of the parameter**
    /// </summary>
    public string MyProperty { get; set; }
}

这可能不雇用Sr.Skeet吗?

asp.net-web-api owin swagger swashbuckle
2个回答
21
投票

嗯...所以也许如果其他人碰到这个。

基本上我找到了一种方法可以完成,我意识到为什么默认情况下没有这样做。不确定它是否是最好的方法,但在这里它。

在我的解决方案中,POCO位于与实际API分开的项目中,因此,未包含MyAwesomeModel的注释描述,因为没有为类和属性生成XML节点。因此,在我的POCO所在的单独项目中,我修改了属性以生成XML。

  1. 为POCO所在的项目生成XML

Output XML for the project where model classes are located

  1. 确保将XML复制到您希望Swashbuckle查找的任何路径。我在项目属性中使用了Post-build event command line;

copy "$(SolutionDir)MyAwesomeProjectWithPocos\bin\MyAwesomeProjectWithPocos.xml" "$(ProjectDir)\bin\MyAwesomeProjectWithPocos.xml"

Post-build event to copy the XML file to the same bin folder as the API xml file

  1. 修改SwaggerConfig以包含此XML

config.EnableSwagger(c =>
{
    c.SingleApiVersion("v1", "My Api Name");
    c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
    c.IncludeXmlComments(GetXmlCommentsPath());
    c.IncludeXmlComments(GetXmlCommentsPathForModels());

}).EnableSwaggerUi(c => { });

现在,在Swagger页面上,如果我从Model Schema切换到Model,我现在可以阅读整个模型和属性描述。

Click models to see model and property comments

当然,没有要求复制XML文件,可能只是指向步骤#3 GetXmlCommentsPathForModels());中的正确位置,但这是我的选择。


0
投票

如果你已经把下面的声明

c.IncludeXmlComments(GetXmlCommentsPath());

是否可以检查xml注释路径方法是否返回放置Project XML文档文件的xml文件的路径?

© www.soinside.com 2019 - 2024. All rights reserved.