引入Nuget包
dotnet add package Swashbuckle.AspNetCore --version 5.5.1
dotnet add package Microsoft.AspNetCore.Mvc.Versioning --version 4.1.1
dotnet add package Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer --version 4.1.1
ConfigureServices
// API版本控制
services.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
}).AddVersionedApiExplorer(o =>
{
o.GroupNameFormat = "'v'V";
});
services.AddSwaggerGen(c =>
{
var providr = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in providr.ApiVersionDescriptions)
{
c.SwaggerDoc(description.GroupName, new OpenApiInfo
{
Title = $"Api接口 v{description.ApiVersion}",
Version = description.ApiVersion.ToString()
});
}
c.OperationFilter<RemoveVersionFromParameter>();
c.DocumentFilter<ReplaceVersionWithExactValueInPath>();
// 添加身份认证
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Description = ""
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{ }
}
});
//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
foreach (var module in GlobalConfiguration.Modules)
{
#if DEBUG
var xmlPath = Path.Combine(GlobalConfiguration.ContentRootPath, $"bin/Debug/netcoreapp3.1/{module.Id}.xml");
#else
var xmlPath = Path.Combine(GlobalConfiguration.ContentRootPath, $"{module.Id}.xml");
#endif
if (File.Exists(xmlPath))
{
c.IncludeXmlComments(xmlPath);
}
}
});
Configure
app.UseSwagger();
app.UseSwaggerUI(c =>
{
var provider = app.ApplicationServices.GetService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions)
{
c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"Api接口 v{description.GroupName}版本");
}
});
RemoveVersionFromParameter
public class RemoveVersionFromParameter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var versionParameter = operation.Parameters.Single(p => p.Name == "version");
operation.Parameters.Remove(versionParameter);
}
}
ReplaceVersionWithExactValueInPath
public class ReplaceVersionWithExactValueInPath : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var paths = new OpenApiPaths();
foreach (var path in swaggerDoc.Paths)
{
paths.Add(path.Key.Replace("v{version}", $"v{swaggerDoc.Info.Version}"), path.Value);
}
swaggerDoc.Paths = paths;
}
}
TestController
[ApiController]
[ApiVersion("1")]
[ApiVersion("2")]
[Route("api/v{version:apiVersion}/test")]
public class TestApiController : ControllerBase
{
[HttpGet]
[MapToApiVersion("1")]
public IActionResult Get(){
return Ok();
}
[HttpGet]
[MapToApiVersion("2")]
public IActionResult Get2(){
return Ok();
}
}
本文介绍了如何在ASP.NET Core项目中配置Swagger,以支持API版本化。首先,通过添加Swashbuckle.AspNetCore和Microsoft.AspNetCore.Mvc.Versioning相关的Nuget包来引入必要的依赖。接着,在`ConfigureServices`方法中注册API版本管理和Swagger服务。然后,在`Configure`方法中配置SwaggerUI,以展示API版本。同时,使用`RemoveVersionFromParameter`和`ReplaceVersionWithExactValueInPath`方法调整API版本参数处理。最后,创建一个`TestController`来演示版本化的API操作。
278

被折叠的 条评论
为什么被折叠?



