实现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 }; } } }
controller的命名空间后加版本号,controller上必须添加RouteAttribute,Action上必须添加路由:
namespace MVCCore3._1Demo.Controllers.v1 { [Route("api/[controller]")] public class HomeController : Controller { [HttpGet("index")] public IActionResult Index() { return View(); } } }
也可以使用中间件实现webapi版本号 https://www.cnblogs.com/lonelyxmas/p/10325436.html