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

时间:2023-03-10 05:21:36
为asp.net core 自定义路由动态修改

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

  

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

    public class RouteConvention : IApplicationModelConvention
{
private readonly AttributeRouteModel _centralPrefix; public RouteConvention(IRouteTemplateProvider routeTemplateProvider)
{ _centralPrefix = new AttributeRouteModel(routeTemplateProvider);
} //接口的Apply方法
public void Apply(ApplicationModel application)
{
application.Controllers.Where(d => !d.ControllerName.Contains("Base") &&
d.Attributes.Any(a => a.ToString().Contains(
"ApiControllerAttribute")))
.Each(controller =>
{
controller.Selectors
.Each(selectorModel =>
{
                //修改路由
selectorModel.AttributeRouteModel = _centralPrefix;
});
});
}
}

然后我们在statup中 配置mvcoption

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