我在我的网站中使用路由约束,现在我需要使用属性路由。
路由约束类:
public class BusConstraint : IRouteConstraint
{
private RouteDB routeDb = new RouteDB();
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values[parameterName] != null)
{
var permalink = values[parameterName].ToString();
try
{
List<AdakDbConnect.RouteTable> routeTables;
if (HttpContext.Current.Cache["RouteTables"] == null)
{
routeTables = routeDb.GetRouteTables(AdakDbDll.Username, AdakDbDll.Password);
HttpContext.Current.Cache.Add("RouteTables", routeTables, null, DateTime.Now.AddMinutes(45), TimeSpan.Zero, CacheItemPriority.Normal, null);
}
else
{
routeTables = HttpContext.Current.Cache["RouteTables"] as List<AdakDbConnect.RouteTable>;
}
RouteTable Route = routeTables?.FirstOrDefault(p => p.Link == permalink && p.Controlller == "Bus");
if (Route != null)
{
return true;
}
}
catch (System.Exception)
{
}
return false;
}
return false;
}
}
对于属性路由,请使用上面的代码操作:
[Route("Bus")]
[Route("Bus/index")]
[Route("Bus/{From:int}/{To:int}/{Date:int}/{IsForeign:int:range(0,1)}/{Title}")]
曾经的 Attribute Routing 和 Route Constraint 目前单独工作。但是当我一起使用时,例如这种情况下,属性路由只起作用,而路由约束不起作用。
路由配置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//---------------------BusRoute---------------------------
routes.MapRoute(
name: "BusRoute",
url: "{*permalink}",
defaults: new { controller = "Bus", action = "Index" },
constraints: new { permalink = new BusConstraint() },
namespaces: new[] { "TravelEnterProject.Controllers" }
);
}
如何同时使用路由约束和属性路由?