Asp.Net Core中使用ModelConvention为webapi添加版本号
2021-03-03 12:28
标签:demo return mvcc dex 部分 rem tor 版本 const controller的命名空间后加版本号,controller上必须添加RouteAttribute,Action上必须添加路由: 也可以使用中间件实现webapi版本号 https://www.cnblogs.com/lonelyxmas/p/10325436.html Asp.Net Core中使用ModelConvention为webapi添加版本号 标签:demo return mvcc dex 部分 rem tor 版本 const 原文地址:https://www.cnblogs.com/fanfan-90/p/12977394.html实现IApplicationModelConvention接口:
public class NameSpaceVersionRoutingConvention:IApplicationModelConvention
{
private readonly string apiPrefix;
private const string urlTemplate = "{0}/{1}/{2}";
public NameSpaceVersionRoutingConvention(string apiPrefix = "api")
{
this.apiPrefix = apiPrefix;
}
public void Apply(ApplicationModel application)
{
foreach (var controller in application.Controllers)
{
var hasRouteAttribute = controller.Selectors
.Any(x => x.AttributeRouteModel != null);
if (!hasRouteAttribute)
{
continue;
}
var nameSpaces = controller.ControllerType.Namespace.Split(‘.‘);
//获取namespace中版本号部分
var version = nameSpaces.FirstOrDefault(x => Regex.IsMatch(x, @"^v(\d+)$"));
if (string.IsNullOrEmpty(version))
{
continue;
}
string template = string.Format(urlTemplate, apiPrefix, version,
controller.ControllerName);
controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel()
{
Template = template
};
}
}
}
namespace MVCCore3._1Demo.Controllers.v1
{
[Route("api/[controller]")]
public class HomeController : Controller
{
[HttpGet("index")]
public IActionResult Index()
{
return View();
}
}
}
文章标题:Asp.Net Core中使用ModelConvention为webapi添加版本号
文章链接:http://soscw.com/index.php/essay/59519.html