为asp.net core 自定义路由动态修改

根据IApplicationModelConvention 接口 实现相应的方法 

 1  

/// <summary>
/// 定义个类RouteConvention,private 来实现 IApplicationModelConvention 接口
/// </summary>


    public
class RouteConvention : IApplicationModelConvention 2 { 3 private readonly AttributeRouteModel _centralPrefix; 4 5 public RouteConvention(IRouteTemplateProvider routeTemplateProvider) 6 { 7 8 _centralPrefix = new AttributeRouteModel(routeTemplateProvider); 9 } 10 11 //接口的Apply方法 12 public void Apply(ApplicationModel application) 13 { 14 application.Controllers.Where(d => !d.ControllerName.Contains("Base") && 15 d.Attributes.Any(a => a.ToString().Contains( 16 "ApiControllerAttribute"))) 17 .Each(controller => 18 { 19 controller.Selectors 20 .Each(selectorModel => 21 {
                //修改路由
26 selectorModel.AttributeRouteModel = _centralPrefix; 27 }); 28 }); 29 } 30 }

然后我们在statup中 配置mvcoption

servers.AddMvc(opts=>{ 
  string apirouter = configuration["apirouter"];
                if (apirouter.IsNullOrEmpty())
                {
                    apirouter = "api/v{version}/[controller]";
                }
// 添加我们自定义 实现IApplicationModelConvention的RouteConvention
            opts.Conventions.Insert(0, new RouteConvention(new RouteAttribute(apirouter)));
}

 

posted @ 2018-09-14 00:59  SpeakHero  阅读(1707)  评论(0编辑  收藏  举报