/// <summary> /// 版本控制 /// </summary> public static class MvcOptionsExtensions { public static void UseGeneralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute) { // 添加我们自定义 实现IApplicationModelConvention的RoutePrefixConvention opts.Conventions.Add(new RoutePrefixConvention(routeAttribute)); } public static void UseGeneralRoutePrefix(this MvcOptions opts, string prefix) { // 添加我们自定义 实现IApplicationModelConvention的RouteAttribute opts.UseGeneralRoutePrefix(new RouteAttribute(prefix)); } } /// <summary> /// 全局路由前缀配置 /// </summary> public class RoutePrefixConvention : IApplicationModelConvention { /// <summary> /// 定义一个路由前缀变量 /// </summary> private readonly AttributeRouteModel _routePrefix; /// <summary> /// 调用时传入指定的路由前缀 /// </summary> /// <param name="route"></param> public RoutePrefixConvention(IRouteTemplateProvider route) { _routePrefix = new AttributeRouteModel(route); } /// <summary> /// 接口的Apply方法 /// </summary> /// <param name="application"></param> public void Apply(ApplicationModel application) { //遍历所有的 Controller foreach (var selector in application.Controllers.SelectMany(c => c.Selectors)) { if (selector.AttributeRouteModel != null) { selector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_routePrefix, selector.AttributeRouteModel); } else { selector.AttributeRouteModel = _routePrefix; } } } }
在Startup文件中配置
public void ConfigureServices(IServiceCollection services) { //#region WkHtmlWrapper //services.UseWkHtmlConverter(); //#endregion //注配置文件appsettings.json services.AddSingleton(new ConfigExtensions(Env.ContentRootPath)); #region 所有控制器添加前缀 //MVC service registration //https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#mvc-service-registration services.AddControllersWithViews(o => { o.UseGeneralRoutePrefix("api/v{version:apiVersion}"); }); services.AddApiVersioning(o => o.ReportApiVersions = true); #endregion }
评论区