tags:

views:

426

answers:

2

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.

+1  A: 

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
        //...
Piotr Czapla
Thanks, this solution looks interesting. But its a pity there is no 'lightweight' method that does not require mocking, because I use Mocks in my unit tests but not in general code. Looks like I should.
Roman
I've had similar concerns and finally decided to pass serialized RouteCollection between requests.
Piotr Czapla
+2  A: 

Roman, I've figured out a solution that don't need mocking. Take a look below:

var request = new HttpRequest(null, "http://localhost:3333/Home/About", "testvalue=1");
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var values = routeData.Values;
// The following should be true for initial version of mvc app.
values["controller"] == "Home"
values["action"] == "Index"

Hope that will help.

Piotr Czapla
Piotr, thank you very much for help. This solution looks great
Roman