【发布时间】:2020-09-22 05:08:43
【问题描述】:
我已经使用 Swashbuckle 和 MultipleApiVersions 实现了 Swagger,它就像一个魅力。但是我觉得当前设置需要 api-version 请求参数有点难看。我假设版本可以由 url /api/V1/Test 确定。
如何去掉 api-version 参数并指示 swagger 以 URL 为基础?
private static void SetupApiVersioningAndSwagger(IAppBuilder builder, AutofacWebApiDependencyResolver resolver)
{
// we only need to change the default constraint resolver for services that want urls with versioning like: ~/v{version}/{controller}
var constraintResolver = new DefaultInlineConstraintResolver() { ConstraintMap = { ["apiVersion"] = typeof(ApiVersionRouteConstraint) } };
var configuration = new HttpConfiguration();
configuration.DependencyResolver = resolver;
var httpServer = new HttpServer(configuration);
// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
configuration.AddApiVersioning(o =>
{
o.ReportApiVersions = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
o.AssumeDefaultVersionWhenUnspecified = true;
});
configuration.MapHttpAttributeRoutes(constraintResolver);
// add the versioned IApiExplorer and capture the strongly-typed implementation (e.g. VersionedApiExplorer vs IApiExplorer)
// note: the specified format code will format the version as "'v'major[.minor][-status]"
var apiExplorer = configuration.AddVersionedApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
// note: this option is only necessary when versioning by url segment. the SubstitutionFormat
// can also be used to control the format of the API version in route templates
options.SubstituteApiVersionInUrl = true;
});
configuration.EnableSwagger(
"{apiVersion}/swagger",
swagger =>
{
// build a swagger document and endpoint for each discovered API version
swagger.MultipleApiVersions(
(apiDescription, version) => apiDescription.GetGroupName() == version,
info =>
{
foreach (var group in apiExplorer.ApiDescriptions)
{
var description = string.Empty;
if (@group.IsDeprecated)
{
description += "This API version has been deprecated.";
}
info.Version(@group.Name, $"Force Search API v{@group.ApiVersion}")
.Description(description);
}
});
swagger.UseFullTypeNameInSchemaIds();
})
.EnableSwaggerUi(swagger => swagger.EnableDiscoveryUrlSelector());
builder.UseWebApi(httpServer);
}
【问题讨论】:
-
您能否显示您的控制器的代码,或者更好地创建一个项目来重现您的问题...我这里有一个多版本示例项目,但我没有遇到这个问题:swagger-net-test-multiapiversions.azurewebsites.net/swagger/ui/…跨度>
标签: asp.net-web-api swagger swashbuckle api-versioning