0

In Global.asax we register routes using:

MapRoute(this System.Web.Routing.RouteCollection routes, 
    string name, 
    string url, 
    object defaults, 
    string[] namespaces)

Is there a way to retrieve the string url from code? Specifically, I am interested in getting route segments from the urls for registered routes like this:

"customRoutePrefix/{controller}/{action}/{id}"

I need to look up "customRoutePrefix" or the equivalent for any registered routes.

I thought I might be able to use System.Web.Routing.RouteTable.Routes to do this, but I haven't found it in there.

Is this possible / how should I do this?

1 Answer 1

1

Yes.

You can use:

this.RouteData.Values["segment name"]

For example,

this.RouteData.Values["controller"];

Edit 1

This piece of code will do the trick to retrieve all the registered routes URL's

var res = new List<string>();

foreach (var item in RouteTable.Routes)
{
    var r = (Route)item;

    res.Add(r.Url);
}

this.ViewBag.Res = res;

In your view:

@foreach (var item in this.ViewBag.Res)
{
    <div>@item</div>
}

Results:

Chapter14/{controller}/{action}/{id}
Movies/{controller}/{action}/{id}
api/{controller}/{id}
{resource}.axd/{*pathInfo}
{resource}.svc/{*pathInfo}
{controller}/{action}/{id}
wcf/{*pathInfo}
Sign up to request clarification or add additional context in comments.

3 Comments

For the case "customUnknownPrefix/{controller}/{action}/{id}" how would I access the first segment? In this case the value I'm looking for would be "customUnknownPrefix" but it could be anything that gets registered.
Well since that part is not a part of the route values, instead it's a static segment probably your best shot is by inspecting the this.Request.RawUrl or this.Request.Url.Segments
It is part of the route Url that was defined when I registered the route using MapRoute(). My question is how I would get the list of all route urls from the registered routes. this.Request.RawUrl and this.Request.Url.Segments will only return values for the current url... not all of the registered routes. I need to be able to get this list of urls without a request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.