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

Jax*_*ian 3 rest asp.net-web-api swagger-ui swashbuckle

我正在使用新的Azure API应用程序(Visual Studio 2013中的模板,带有15年3月24日起的新SDK),并且我希望我的Swagger UI组按版本号进行调用。就我而言,我目前正在通过URI进行版本控制(我知道REST纯粹主义者会告诉我不要这样做-请不要在此处尝试“更正我的错误”)。例如,我可能有以下电话:

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}
Run Code Online (Sandbox Code Playgroud)

从功能上来说,这很棒!(是的,我知道有些人会畏缩。对不起,这会伤害您的感觉。)但是,我的问题是使用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());
Run Code Online (Sandbox Code Playgroud)

我不明白的是,我怎样才能将所有“最新”分组,然后将所有v1分组在一起,然后将所有v2分组在一起,依此类推。

我怎样才能做到这一点?如果绝对必须在路径中添加单词“ latest”(或equiv)来代替版本号,则可以这样做,但我不想这样做。

Sco*_*ott 5

我相信您想要做的是取消注释SwaggerConfig.cs中的一行以下几行

c.OrderActionGroupsBy(new DescendingAlphabeticComparer());
Run Code Online (Sandbox Code Playgroud)

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

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您已经足够问这个问题了,那么我可以将sort实现留给您。:-)