rest - 如何让 Swashbuckle 使用 Swagger UI 按版本分组?

标签 rest asp.net-web-api swagger-ui swashbuckle

我正在使用新的 Azure API 应用程序(Visual Studio 2013 中的模板,带有来自 2015 年 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}

从功能上讲,这很好用! (是的,我知道你们中的一些人会畏缩。对不起,这会伤害你们的感情。)但是,我的问题是 Swagger UI 组织。默认情况下,Swagger UI 按 Controller 名称(在本例中为 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());

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

我怎样才能做到这一点?如果绝对必须要求我在路径中添加“最新”(或等效)一词来代替版本号,那么我可以这样做,但我不想这样做。

最佳答案

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

c.OrderActionGroupsBy(new DescendingAlphabeticComparer());

除了您将类的名称更改为 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));
    }
}

如果你问这个问题已经足够了,我相信我可以把排序实现留给你。 :-)

关于rest - 如何让 Swashbuckle 使用 Swagger UI 按版本分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336016/

相关文章:

rest - 如果 REST 应用程序应该是无状态的,那么如何管理 session ?

Web API 中实体的 RESTful 归档

rest - 如何将 Swagger OpenAPI 规范添加到 Spring Boot 项目中?

go - 如何将 swagger ui 与 golang 和 goa 集成

rest - 在没有用户委托(delegate)的情况下如何使用OAuth? -- 微软图形API

java - 使用 RestTemplate 进行基本身份验证 - 编译错误 - 构造函数 HttpClient() 不可见

web-services - DAO 微服务是微服务架构中的好方法吗?

c# - 来自 response.Content.ReadAsStreamAsync() 的流不可随机读取

c# - 异步 Web API 端点

java - 无法访问 SwaggerUI index.html 页面,但可以打开 api-docs (Spring - Boot)