asp.net-mvcroutetable

retrieve route values from RouteTable


i want retrieve route values from RouteTable, but it's null. can anybody help?

public static class GetRouteValues
{
    public static string GetSomeValue()
    {
        RouteCollection routes = RouteTable.Routes;
        var value = routes["somevalue"].ToString();
        return value;
    }
}

i want retrieve this value for using in global.asax file and set as default value for some routes value.

string value = GetRouteValues.GetSomeValue();
routes.MapRoute(null,
                        "{_value}/home",
                        new
                        {
                            _value = value,
                            controller = "home",
                            action = "index"
                        });

Solution

  • Ok if you are trying to get the current route, you can do this from within a controller....

    var completeRoute = this.ControllerContext.RouteData.Route;
    //or
    var justValue = this.ControllerContext.RouteData.Values["value"]
    

    Let me know if thats what you are after...

    UPDATE:

    Ok I think this should do what you are after. You should be able to use this in a static method without passing in any context object.

    var httpContext = new HttpContextWrapper(HttpContext.Current); 
    var requestContext = new RequestContext(httpContext, new RouteData());
    var completeRoute = requestContext.RouteData.Route;
    var justValue = requestContext.RouteData.Values["value"];
    

    Hope that helps.