How can I iterate through all defined MVC routes?

0

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

asp.net
asp.net-mvc
asp.net-mvc-5.2
asked on Stack Overflow Jun 18, 2017 by Yovav • edited Jun 19, 2017 by Yovav

1 Answer

1

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>
}
answered on Stack Overflow Jun 19, 2017 by Yovav

User contributions licensed under CC BY-SA 3.0