如何在Swashbuckle中为包含OWIN的WebApi 2生成Swagger文档中包含类和属性描述?

时间:2016-09-19 14:54:37

标签: asp.net-web-api owin swagger swashbuckle

在你想到它之前,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,这可能吗?

2 个答案:

答案 0 :(得分:20)

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

基本上我找到了一种可以做到这一点的方法,并且我意识到为什么默认情况下没有这样做。不知道这是不是最好的方法,但现在就这样了。

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

  1. 为POCO所在的项目生成XML
  2. Output XML for the project where model classes are located

    1. 确保将XML复制到您希望Swashbuckle查找的任何路径。我在项目属性中使用了Post-build event command line;
    2. 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
      2. 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());中的正确位置,但这是我的选择。

答案 1 :(得分:0)

如果你已经提出以下声明

c.IncludeXmlComments(GetXmlCommentsPath());

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