using CoreAgent.Infrastructure.Options;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CoreAgent.Infrastructure.Extensions.ServiceCollection;
///
/// API版本服务扩展方法
///
public static class ApiVersioningServiceExtensions
{
///
/// 添加API版本服务
///
/// 服务集合
/// 服务集合
public static IServiceCollection AddApiVersioningService(this IServiceCollection services, IConfiguration config)
{
var settings = config.GetSection("ApiVersioning").Get() ?? new ApiVersioningSettings();
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = ApiVersion.Parse(settings.DefaultVersion);
options.AssumeDefaultVersionWhenUnspecified = settings.AssumeDefaultVersionWhenUnspecified;
options.ReportApiVersions = settings.ReportApiVersions;
options.ApiVersionReader = ApiVersionReader.Combine(
settings.ShowVersionInUrl ? new UrlSegmentApiVersionReader() : null,
settings.ShowVersionInQueryString ? new QueryStringApiVersionReader("api-version") : null,
settings.ShowVersionInHeader ? new HeaderApiVersionReader("api-version") : null,
settings.ShowVersionInMediaType ? new MediaTypeApiVersionReader("version") : null
);
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
return services;
}
public static IApplicationBuilder UseApiVersioningExtension(this IApplicationBuilder app)
{
// 可以在这里添加版本控制相关的中间件
return app;
}
}