0

我正在使用名为AttributeRouting的第三方nuget,它使用属性注册路由。我有一个独特的情况,我需要从Application_Start或类似的路由表中删除路由。如何才能做到这一点?如何在运行时删除路由?

我提供了我想要删除的路线的屏幕截图。我甚至将它命名为“RemoveMePlease”。 enter image description here

感谢

回答

0
public class MvcApplication : admin.project.Global 
{ 
    protected override void Application_Start() 
    { 
     base.Application_Start(); 

     int iRoute = 0; 
     while (iRoute < RouteTable.Routes.Count) 
     { 
      bool isLastRoute = (iRoute == (RouteTable.Routes.Count - 1)); 

      RouteBase route = RouteTable.Routes[iRoute]; 

      if (!isLastRoute && route is AttributeRoute) 
      { 
       AttributeRoute currentRoute = route as AttributeRoute; 
       int maxRouteIndex = RouteTable.Routes.Count - 1; 
       for (int iDup = maxRouteIndex; iDup >= (iRoute + 1); iDup--) 
       { 
        if (RouteTable.Routes[iDup] is AttributeRoute) 
        { 
         var potentialDupRoute = RouteTable.Routes[iDup] as AttributeRoute; 

         if (currentRoute.Url.Equals(potentialDupRoute.Url)) //-- routes match on url 
         { 
          //-- do httpMethods also match? 
          //-- AttributeRouting <=3.1 
          ICollection<string> currentHttpMethods = ((currentRoute.Constraints["httpMethod"]) as HttpMethodConstraint).AllowedMethods; 
          ICollection<string> potentialHttpMethods = ((potentialDupRoute.Constraints["httpMethod"]) as HttpMethodConstraint).AllowedMethods; 

          //-- AttributeRouting > 3.1 
          ICollection<string> currentHttpMethods = (currentRoute.Constraints["inboundHttpMethod"] as AttributeRouting.Web.Mvc.Constraints.InboundHttpMethodConstraint).AllowedMethods; 
          ICollection<string> potentialHttpMethods = (potentialDupRoute.Constraints["inboundHttpMethod"] as AttributeRouting.Web.Mvc.Constraints.InboundHttpMethodConstraint).AllowedMethods; 


          IEnumerable<string> matchedHttpMethods = currentHttpMethods.Intersect(potentialHttpMethods); 

          //-- remove the route 
          if (matchedHttpMethods.Count() == currentHttpMethods.Count()) RouteTable.Routes.Remove(currentRoute); 
         } 
        } 
       } 
      } 

      iRoute++; 
     } 
    } 
}