1、新建RouteConventio.cs文件
/// <summary> /// 全局路由前缀配置 /// </summary> public class RouteConventio:IApplicationModelConvention { /// <summary> /// 定义一个路由前缀变量 /// </summary> private readonly AttributeRouteModel _centralPrefix; /// <summary> /// 调用时传入指定的路由前缀 /// </summary> /// <param name="routeTemplateProvide"></param> public RouteConventio(IRouteTemplateProvider routeTemplateProvide) { _centralPrefix = new AttributeRouteModel(routeTemplateProvide); } /// <summary> /// 接口的Apply方法,在这个方法中根据情况来添加api 路由前缀 /// </summary> /// <param name="application"></param> public void Apply(ApplicationModel application) { //遍历所有的Controller foreach (var controllers in application.Controllers) { //1、已经标记RouteAttribute 的 Controller //如果在控制器中已经标注有路由了,则会在路由的前面再添加指定的路由内容 var matchedSelectors = controllers.Selectors.Where(x => x.AttributeRouteModel != null).ToList(); if (matchedSelectors.Any()) { foreach (var selectorModel in matchedSelectors) { //在当前路由上再添加一个路由前缀 selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix, selectorModel.AttributeRouteModel); } } //2、没有标记RouteAttribute 的 Controller var unmatchedSelectors = controllers.Selectors.Where(x => x.AttributeRouteModel == null).ToList(); if (unmatchedSelectors.Any()) { foreach (var selectorModel in unmatchedSelectors) { // 添加一个 路由前缀 selectorModel.AttributeRouteModel = _centralPrefix; } } } } }2、在Program.cs修改内容
builder.Services //全局路由前缀配置 .AddControllers(option => { //api/就是在所有路由前面增加的名称 option.Conventions.Insert(0, new RouteConventio(new RouteAttribute("api/"))); }) ////在这里解决中文乱码问题 .AddJsonOptions(options => { options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); });
标签:selectorModel,前缀,RouteConventio,var,全局,路由,AttributeRouteModel From: https://www.cnblogs.com/ahao214/p/17574322.html