如何使用aspnet ApiVersioning在Swashbuckle中配置MultipleApiVersions [英] How to configure MultipleApiVersions in Swashbuckle using aspnet ApiVersioning
问题描述
我如何配置 swashbuckle
与 Aspnet API
一起使用? https://github.com/Microsoft/aspnet-api-versioning
How do I configure swashbuckle
to work with Aspnet API
verisoning?
https://github.com/Microsoft/aspnet-api-versioning
在我的 Startup.cs
中,我有以下代码用于初始化基于属性的路由,api版本控制和调整.
In my Startup.cs
I have the following code to initialize attribute based routing, api versioning, and swagger.
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint )
}
};
config.MapHttpAttributeRoutes(constraintResolver);
config.AddApiVersioning();
config.EnableSwagger(c =>
{
c.MultipleApiVersions(
(apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
(vc) =>
{
vc.Version("v1", "Swashbuckle Dummy API V1");
vc.Version("v2", "Swashbuckle Dummy API V2");
});
}
public static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
{
var versionConstraint = (apiDesc.Route.Constraints.ContainsKey("apiVersion"))
? apiDesc.Route.Constraints["apiVersion"] as RegexRouteConstraint
: null;
return (versionConstraint == null)
? false
: versionConstraint.Pattern.Split('|').Contains(targetApiVersion);
}
当ResolveVersionSupportByRouteConstraintmethod触发时,路由模板包括文字api字符串"api/v {version}/users".我的用户控制器装饰为[ApiVersion("1.0")],并且定义了以下路由[Route("api/v {version:apiVersion}/users)].当我用邮递员访问api/v1/users时,该调用有效,但我不知道如何在Swashbuckle/Swagger中使用该功能.
When the ResolveVersionSupportByRouteConstraintmethod fires the route template includes the literal api string "api/v{version}/users" My users controller is decorated with [ApiVersion("1.0")] and I have the following route defined [Route("api/v{version:apiVersion}/users")]. When I hit api/v1/users with postman the call works, but i cannot figure out how to get this working with Swashbuckle/Swagger.
我希望我的招摇的文档看起来像asp.net核心api样板的示例,但我将Owin与owin启动类而不是.net核心一起使用:
I want my swagger documentation to look like the example for the asp.net core api boilerplate, except I am using Owin with the owin startup class instead of .net core: https://github.com/ASP-NET-Core-Boilerplate/Templates/blob/master/MVC%206%20API.md
推荐答案
You can find examples here This is how I done this in startup of self hosted owin app:
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
//configure your app
config.AddApiVersioning(o =>
{
o.ReportApiVersions = true;
o.ApiVersionReader = new UrlSegmentApiVersionReader();
});
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap = { ["apiVersion"] = typeof(ApiVersionRouteConstraint) }
};
config.MapHttpAttributeRoutes(constraintResolver);
SwaggerConfiguration.Configure(config);
appBuilder.UseWebApi(config);
}
swagger的配置非常简单,主要部分在这里VersionedApiExplorer(确保您正确传递了api的groupnameformat,我的格式是v1,v2等):
Configuration of swagger is very simple, main part here VersionedApiExplorer(ensure, that you passed right groupnameformat of your api, my format was v1, v2, etc):
public static class SwaggerConfiguration
{
public static void Configure(HttpConfiguration config)
{
var apiExplorer = config.AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'V");
config.EnableSwagger(
swagger =>
{
swagger.MultipleApiVersions(
(apiDesc, targetApiVersion) => apiDesc.GetGroupName() == targetApiVersion,
versionBuilder =>
{
foreach (var group in apiExplorer.ApiDescriptions)
{
var description = "";
if (group.IsDeprecated) description += "This API deprecated";
versionBuilder.Version(group.Name, $"Service API {group.ApiVersion}")
.Description(description);
}
});
swagger.DocumentFilter<VersionFilter>();
swagger.OperationFilter<VersionOperationFilter>();
})
.EnableSwaggerUi(cfg => cfg.EnableDiscoveryUrlSelector());
}
在控制器中添加属性ApiVersion和RoutePrefix
In controller add attributes ApiVersion and RoutePrefix
[ApiVersion("1")]
[RoutePrefix("api/v{version:apiVersion}/history")]
public class HistoryController: ApiController
如果您对VersionFilter和VersionOperationFilter感到困惑,则有相应的代码.此过滤器会大范围地修改生成的路线和参数(但您的路线看起来像/v {version}/{actionName}并包含所需的参数版本)
If you confused about VersionFilter and VersionOperationFilter there is code for that. This filters modifies resulting routes and parameters in swagger(without that your route will look like /v{version}/{actionName} and contain required parameter version)
public class VersionFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths = swaggerDoc.paths
.ToDictionary(
path => path.Key.Replace("v{version}", swaggerDoc.info.version),
path => path.Value
);
}
}
public class VersionOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var version = operation.parameters?.FirstOrDefault(p => p.name == "version");
if (version != null)
{
operation.parameters.Remove(version);
}
}
}
这篇关于如何使用aspnet ApiVersioning在Swashbuckle中配置MultipleApiVersions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!