Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String URL to RouteValueDictionary

Tags:

asp.net-mvc

Is there as easy way to convert string URL to RouteValueDictionary collection? Some method like UrlToRouteValueDictionary(string url).

I need such method because I want to 'parse' URL according to my routes settings, modify some route values and using urlHelper.RouteUrl() generate string URL according to modified RouteValueDictionary collection.

Thanks.

like image 634
Roman Avatar asked Sep 26 '09 16:09

Roman


2 Answers

You would need to create a mocked HttpContext as routes constrains requires it.

Here is an example that I use to unit test my routes (it was copied from Pro ASP.Net MVC framework):

        RouteCollection routeConfig = new RouteCollection();
        MvcApplication.RegisterRoutes(routeConfig);
        var mockHttpContext = new MockedHttpContext(url);
        RouteData routeData = routeConfig.GetRouteData(mockHttpContext.Object);
        // routeData.Values is an instance of RouteValueDictionary
        //...
like image 108
Piotr Czapla Avatar answered Oct 07 '22 23:10

Piotr Czapla


I wouldn't rely on RouteTable.Routes.GetRouteData from previous examples because in that case you risk missing some values (for example if your query string parameters don't fully fit any of registered mapping routes). Also, my version doesn't require mocking a bunch of request/response/context objects.

public static RouteValueDictionary UrlToRouteValueDictionary(string url)
{
    int queryPos = url.IndexOf('?');

    if (queryPos != -1)
    {
        string queryString = url.Substring(queryPos + 1);
        var valuesCollection = HttpUtility.ParseQueryString(queryString);
        return new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k]));
    }

    return new RouteValueDictionary();
}
like image 42
Sergei Avatar answered Oct 08 '22 01:10

Sergei