1

I'm trying to get a list of all routes of my website in order to check if a URL is taken or not, for example, I allow mydomain.com/username - so I want to make sure username can be used and it is not some used route like mydomain.com/contact

How can I iterate through all defined MVC routes?

UPDATE 1:

For some reason the code in the suggested answer is breaking for me with Exception (0x80004002) - Unable to cast object of type 'System.Web.Mvc.Routing.RouteCollectionRoute' to type 'System.Web.Routing.Route'.

I do have some routes RouteTable.Routes.Count, this code below allows me to see that I have different types of objects in it (not sure why)

@foreach (var r in RouteTable.Routes)
{
    // var r = (System.Web.Routing.Route)route; // This is breaking
    <div>@r.ToString()</div>
}

I'm getting things like:

Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataRoute System.Web.Http.WebHost.Routing.HttpWebRoute, System.Web.Mvc.RouteCollectionExtensions+IgnoreRouteInternal, System.Web.Mvc.Routing.RouteCollectionRoute, System.Web.Mvc.Routing.LinkGenerationRoute, System.Web.Routing.Route

it seems like the routes I need are in the System.Web.Mvc.Routing.LinkGenerationRoute type objects

I don't understand why I'm getting different type of objects in RouteTable.Routes, however, if I try to cast to a Route and get the URL I get the Unable to cast exception... Any suggestions?

UPDATE 2:

It works when I add this filter

RouteTable.Routes.OfType< Route >()

I would love to understand why is it needed and what are the other object types in RouteTable.Routes

Yovav
  • 2,557
  • 2
  • 32
  • 53
  • Possible duplicate of [Test if a request's URL is in the Route table](https://stackoverflow.com/questions/36894210/test-if-a-requests-url-is-in-the-route-table) – NightOwl888 Jun 19 '17 at 05:04
  • The code from https://stackoverflow.com/questions/36894210/test-if-a-requests-url-is-in-the-route-table is breaking in my case, I added more details. – Yovav Jun 19 '17 at 10:08
  • Of course, you would never need to loop through the route table. As in [my answer](https://stackoverflow.com/a/37215782/181087), you would call `GetRouteData()` and check it for a non-null response. `GetRouteData()` already loops through the route table and makes the comparison using the *business logic* within the route table. – NightOwl888 Jun 19 '17 at 11:02

1 Answers1

3

Its working when I'm adding this RouteTable.Routes.OfType()

@foreach (var route in RouteTable.Routes.OfType<Route>())
{
    var r = (Route)route;
    <div>@r.Url</div>
}
Yovav
  • 2,557
  • 2
  • 32
  • 53
  • Awesome this helped me fix the [`RouteDebugger` project by Stephen Walther](http://stephenwalther.com/archive/2009/02/06/chapter-2-understanding-routing). It wasn't filtering the `RouteTable.Routes` collection by `NamedRoute` which meant it failed when a projected contained WebApi routes as well. – user692942 Nov 07 '17 at 14:30