我正在努力让Swagger在WebApi中记录多租户路线。我之前使用过这种方法但从未在自托管项目中使用过。似乎永远不会调用MultipleApiVersions
- 当我添加了日志代码时。
StatupConfig.cs
public class StartupConfig
{
private static ILog _logger = LogManager.GetLogger(nameof(StartupConfig));
public void Configure(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Filters.Add(new ApiKeyAuthorizationFilter());
config.Filters.Add(new ApiInvocationMetricsFilter());
var assembly = Assembly.GetExecutingAssembly();
var builder = new ContainerBuilder();
builder.RegisterApiControllers(assembly);
builder.RegisterWebApiFilterProvider(config);
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
appBuilder.UseAutofacMiddleware(container);
appBuilder.UseAutofacWebApi(config);
appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
appBuilder.UseWebApi(config);
config
.EnableSwagger(c =>
{
c.MultipleApiVersions(
ResolveVersionSupportByRouteConstraint,
(vc) =>
{
vc.Version("v2", "API v2");
vc.Version("v1", "API v1");
});
c.RootUrl((message) => ConfigurationManager.AppSettings["SwaggerRoot"]);
c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\API.xml");
c.OperationFilter<AddRequiredApiKeyParameter>();
c.DescribeAllEnumsAsStrings(true);
})
.EnableSwaggerUi(ui =>
{
ui.EnableDiscoveryUrlSelector();
});
}
public static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
{
try
{
var versionConstraint = (apiDesc.Route.Constraints.ContainsKey("apiVersion"))
? apiDesc.Route.Constraints["apiVersion"] as ApiVersionConstraint
: null;
return versionConstraint?.AllowedVersion.Split('|').Select(x => x.ToLowerInvariant()).ToList().Contains(targetApiVersion.ToLowerInvariant()) ?? false;
}
catch (System.Exception excep)
{
_logger.Error("An error occurred resolving version support", excep);
throw;
}
}
}
注意:这比WebApiVersioning早,所以我使用路由约束:
public class ApiVersion2RoutePrefixAttribute : RoutePrefixAttribute
{
private const string RouteBase = "api/{apiVersion:apiVersionConstraint(v2)}";
private const string PrefixRouteBase = "api/{apiVersion:apiVersionConstraint(v2)}/";
public ApiVersion2RoutePrefixAttribute(string routePrefix)
: base(string.IsNullOrWhiteSpace(routePrefix) ? "api/{apiVersion:apiVersionConstraint(v2)}" : "api/{apiVersion:apiVersionConstraint(v2)}/" + routePrefix)
{
}
}
我在这里错过了什么吗?
由于 KH
答案 0 :(得分:0)
通过确保Name
属性中的任何Route
参数在两个控制器版本中都是唯一的,可以解决此问题。我有一个名为Add的操作,两个控制器的Route Name参数为Add,这阻止了Swagger的运行。
即这个
[Route("", Name = nameof(AddAdvertiser))]
更改为此
[Route("", Name = nameof(V1AddAdvertiser))]