You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
2.0 KiB
51 lines
2.0 KiB
7 days ago
|
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;
|
||
|
|
||
|
/// <summary>
|
||
|
/// API版本服务扩展方法
|
||
|
/// </summary>
|
||
|
public static class ApiVersioningServiceExtensions
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 添加API版本服务
|
||
|
/// </summary>
|
||
|
/// <param name="services">服务集合</param>
|
||
|
/// <returns>服务集合</returns>
|
||
|
public static IServiceCollection AddApiVersioningService(this IServiceCollection services, IConfiguration config)
|
||
|
{
|
||
|
var settings = config.GetSection("ApiVersioning").Get<ApiVersioningSettings>() ?? 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;
|
||
|
}
|
||
|
}
|