有可能像 swashbuckle 那样有多个文档端点吗?
options.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
options.SwaggerEndpoint("/swagger/v2/swagger.json", "API v2");
如果是,如何装饰 api 调用,使一些属于一个版本,一些属于另一个版本?
所以根据 Rico Suter 的建议,我所做的有点像这样:
ApiVersionAttribute.cs
public class ApiVersionAttribute:Attribute
{
private List<string> _versions = new List<string>();
public List<string> Versions { get { return _versions; } }
public ApiVersionAttribute(string version) {
Versions.Add(version);
}
}
MyApiVersionProcessor.cs
public string Version { get; set; }
public MyApiVersionProcessor(string version)
{
this.Version = version;
}
public new Task<bool> ProcessAsync(OperationProcessorContext context)
{
bool returnValue = true;
var versionAttributes = context.MethodInfo.GetCustomAttributes()
.Concat(context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes())
.Where(a => a.GetType()
.IsAssignableTo("MapToApiVersionAttribute", TypeNameStyle.Name)
|| a.GetType()
.IsAssignableTo("ApiVersionAttribute", TypeNameStyle.Name)
)
.Select(a => (dynamic)a)
.ToArray();
var versionAttribute = versionAttributes.FirstOrDefault();
if (null == versionAttribute)
{
returnValue = false;
}
else
{
if (ObjectExtensions.HasProperty(versionAttribute, "Versions")
&& Version.Equals(versionAttribute.Versions[0].ToString()))
{
ReplaceApiVersionInPath(context.OperationDescription, versionAttribute.Versions);
}
else {
returnValue = false;
}
}
return Task.FromResult(returnValue);
}
private void ReplaceApiVersionInPath(SwaggerOperationDescription operationDescription,
dynamic versions)
{
operationDescription.Path = operationDescription.Path.Replace("{version:apiVersion}",
versions[0].ToString());
}
}
在我的 Global.asax
// NSwag
// https://github.com/RSuter/NSwag/wiki/OwinGlobalAsax#integration
app.UseSwaggerUi(typeof(WebApiApplication).Assembly, new SwaggerUiSettings
{
//TypeNameGenerator = new MyTypeNameGenerator(),
MiddlewareBasePath = "/swagger",
SwaggerRoute = "/swagger/v1/swagger.json",
Version = "1.0.0.0",
// https://github.com/RSuter/NSwag/wiki/Middlewares
OperationProcessors =
{
new MyApiVersionProcessor("v1")
},
PostProcess = document =>
{
document.BasePath = "/";
document.Produces
= new List<string> { "application/json"
, "text/json"
, "text/html"
, "plain/text"
, "application/xml"};
document.Consumes
= document.Produces;
document.Info.Title = "Document V1";
}
});
app.UseSwaggerUi(typeof(WebApiApplication).Assembly, new SwaggerUiSettings
{
//TypeNameGenerator = new MyTypeNameGenerator(),
MiddlewareBasePath = "/swagger",
SwaggerRoute = "/swagger/v2/swagger.json",
Version = "2.0.0.0",
OperationProcessors =
{
new MyApiVersionProcessor("v2")
},
PostProcess = document =>
{
document.BasePath = "/";
document.Produces
= new List<string> { "application/json"
, "text/json"
, "text/html"};
document.Consumes
= document.Produces;
document.Info.Title = "Document V2";
}
});
并用我的控制器方法装饰
[ApiVersion("v2")]
[ApiVersion("v1")]
等等