如何让 Swashbuckle 让 Swagger UI 按版本分组?

How do I get Swashbuckle to have Swagger UI to group by Version?

我正在使用新的 Azure API 应用程序(Visual Studio 2013 中的模板,带有 2015 年 3 月 24 日的新 SDK 位)并且我想要我的 Swagger UI 按版本号对我的呼叫进行分组。就我而言,我目前正在通过 URI 进行版本控制(我知道 REST 纯粹主义者会告诉我不要这样做——请不要在这里尝试 "correct my error")。例如,我可能有这些电话:

http://example.com/api/Contacts <-- "latest"
http://example.com/api/1/Contacts
http://example.com/api/2/Contacts
http://example.com/api/Contacts{id} <-- "latest"
http://example.com/api/1/Contacts/{id}
http://example.com/api/2/Contacts/{id}

从功能上讲,这很好用! (是的,我知道你们中的一些人会畏缩。抱歉这伤害了你们的感情。)但是,我的问题是 w/Swagger UI 组织。默认情况下,Swagger UI 按控制器名称对这些进行分组(在本例中为 Contacts)。我在 SwaggerConfig.cs 文件中看到我可以更改它:

// Each operation be assigned one or more tags which are then used by consumers for various reasons.
// For example, the swagger-ui groups operations according to the first tag of each operation.
// By default, this will be controller name but you can use the "GroupActionsBy" option to
// override with any value.
//
//c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString());

我不明白的是我如何调整它以将所有 "latest" 组合在一起,然后将所有 v1 组合在一起,然后将所有 v2 组合在一起,等等。

我该怎么做?如果它绝对必须要求我在路径中添加单词 "latest"(或等值)来代替版本号,那么我可以这样做,但我宁愿不必那样做。

我相信您要做的是取消注释 SwaggerConfig.cs

中该行下方几行的行
c.OrderActionGroupsBy(new DescendingAlphabeticComparer());

除非您将 class 的名称更改为 ApiVersionComparer() 之类的名称,然后将其实现为新的 class:

public class ApiVersionComparer : IComparer<string>
{

    public int Compare(string x, string y)
    {
        // Write whatever comparer you'd like to here.
        // Yours would likely involve parsing the strings and having
        // more complex logic than this....
        return -(string.Compare(x, y));
    }
}

如果您已经足够深入地提出这个问题,我相信我可以将排序实现留给您。 :-)