I use Route Constraint in my website and Now I need to use Attribute Routing.
Route Constraint class:
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;
}
}
For Attribute Routing use this code above action :
[Route("Bus")]
[Route("Bus/index")]
[Route("Bus/{From:int}/{To:int}/{Date:int}/{IsForeign:int:range(0,1)}/{Title}")]
Once of Attribute Routing and Route Constraint worked currently alone. But when I use together such as this case Attribute Routing worked Only and Route Constrain don't work.
RouteConfig :
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" }
);
}
How can I use Route Constraint and Attribute Routing together?