一、前言
今天说一下在.netcore3.1的版本下设置统一的API路由。
二、实现
添加MvcOptionsExtensions扩展类
如下:
然后在添加RouteConvention类
如下:
public class RouteConvention : IApplicationModelConvention
{
///
/// 定义一个路由前缀变量
///
private readonly AttributeRouteModel _centralPrefix;
///
/// 调用时传入指定的路由前缀
///
///
public RouteConvention(IRouteTemplateProvider routeTemplateProvider)
{
_centralPrefix = new AttributeRouteModel(routeTemplateProvider);
}
///
/// 接口的Apply方法
///
///
public void Apply(ApplicationModel application)
{
//遍历所有的 Controller
foreach (var controller in application.Controllers){
// 1、已经标记了 RouteAttribute 的 Controller
// 如果在控制器中已经标注有路由了,则会在路由的前面再添加指定的路由内容。
var matchedSelectors = controller.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 = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
if (unmatchedSelectors.Any())
{
foreach (var selectorModel in unmatchedSelectors)
{
// 添加一个 路由前缀
selectorModel.AttributeRouteModel = _centralPrefix;
}
}
}
}
}
在添加完这两个类库后,需要在Startup的ConfigureServices中添加定义统一路由添加如下代码:
services.AddMvc(option => {
option.Filters.Add(typeof(MyAuthorizeFilter));
option.UseCentralRoutePrefix(new RouteAttribute("/api/v1"));//在各个控制器添加前缀(没有特定的路由前面添加前缀)
//opt.UseCentralRoutePrefix(new RouteAttribute("api/[controller]/[action]"));
});
三、运行结果这样就可以设置API的统一路由了。
KEEP THE SKY CLEAR
-六月,春去夏来-
今
日
直
播
课
程
直播内容:设计模式之-抽象工厂的秘密探究
直播时间:今日15:00
主讲人:常老师
扫码进入直播↓
![38337e6610a8dcf38d37c990241b7174.png](https://i-blog.csdnimg.cn/blog_migrate/5cf1970401affb8c013bac914f0c5a3a.png)
![02c14ca6c41f6e5829a1ff0de2b2e6a8.gif](https://i-blog.csdnimg.cn/blog_migrate/8f0c87d7a42f22c54e9da1eba31a6c9c.gif)
基于S7-PLCSIM Advanced搭建S7通信仿真环境
![02c14ca6c41f6e5829a1ff0de2b2e6a8.gif](https://i-blog.csdnimg.cn/blog_migrate/8f0c87d7a42f22c54e9da1eba31a6c9c.gif)
上位机开发之三菱FX3U以太网通信实践
![02c14ca6c41f6e5829a1ff0de2b2e6a8.gif](https://i-blog.csdnimg.cn/blog_migrate/8f0c87d7a42f22c54e9da1eba31a6c9c.gif)
OPCUA+MQTT构建物联网通用框架
![02c14ca6c41f6e5829a1ff0de2b2e6a8.gif](https://i-blog.csdnimg.cn/blog_migrate/8f0c87d7a42f22c54e9da1eba31a6c9c.gif)
基于KepServer实现与S7-1200PLC之间的通信
![ff6e1f84c8ada1f00d30f14c2ca5df4a.gif](https://i-blog.csdnimg.cn/blog_migrate/d055d55aab478c772839d257ac219b16.gif)