ASP.NET MVC: Constructing UrlHelper

I needed to have a class external to the controller’s and views that could generate a correctly formed Url using the UrlHelper.

I found this question on Stackoverflow which helped me with a solution. The solution was as follows:

HttpContextWrapper httpContextWrapper =
    new HttpContextWrapper(HttpContext.Current);

UrlHelper urlHelper = new UrlHelper(
    new RequestContext(
        httpContextWrapper, 
        new RouteData()));

I previously got confused about the RouteData object, but it seems (unless I’m mistaken) to essentially be route values, which in this case i don’t need… Not sure on that though!

As constructed above, the UrlHelper is able to take the RequestContext and get all the registered routes and therefore generate a correctly structured url when you call Action etc.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: