為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)));
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM