Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Create a UrlHelper from a library class in asp.net mvc January 7, 2010

Filed under: Uncategorized — Rupert Bates @ 11:13 am

If you need to get hold of a UrlHelper outside a controller, for instance to work out a url from an action in a library class, you can use the following function:

		public static UrlHelper GetUrlHelper()
			var httpContext = new HttpContextWrapper(HttpContext.Current);
			return new UrlHelper( new RequestContext(httpContext, CurrentRoute(httpContext)));
		public static RouteData CurrentRoute(HttpContextWrapper httpContext)
			return RouteTable.Routes.GetRouteData(httpContext);

3 Responses to “Create a UrlHelper from a library class in asp.net mvc”

  1. Yuriy Says:

    This doesn’t work. Visual studio 2008 asks for CurrentRoute

  2. Rupert Bates Says:

    You’re right I missed that function out, I’ve updated the post to include it.

  3. Thank you so much for this!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s