Search code examples
c#asp.netasp.net-mvcurl-routingasp.net-mvc-routing

Test if a request's URL is in the Route table


I want to test if a URL is part of the routes defined in the Global.asax. This is what I have:

var TheRequest = HttpContext.Current.Request.Url.AbsolutePath.ToString();
var TheRoutes = System.Web.Routing.RouteTable.Routes;

foreach (var TheRoute in TheRoutes)
{
    if (TheRequest  == TheRoute.Url) //problem here
    {
        RequestIsInRoutes = true;
    }
}

The problem is that I can’t extract the URL from the route. What do I need to change?


Solution

  • This is what I ended up doing:

    string TheRequest = HttpContext.Current.Request.Url.AbsolutePath.ToString();
    
    foreach (Route r in System.Web.Routing.RouteTable.Routes)
    {
        if (("/" + r.Url) == TheRequest)
        {
            //the request is in the routes
        }
    }
    

    It's hacky but it works in 3 lines.