Thursday, September 17, 2009 10:41 AM srkirkland

A UrlHelper Extension For Creating Absolute Action Paths in ASP.NET MVC

ASP.NET MVC comes with a UrlHelper class in the System.Web.Mvc.Controller.Url namespace, which you can access through the Url property of any controller.  This provides some handy methods to get the url of an action or route, among other things.  For example, Url.Action(“About”, “Home”) will return the string “/Home/About”, which is the relative url of the About action on the Home controller.

I recently had a need to generate an absolute Url (to put in an email), so I wrote a quick extension method to the UrlHelper class that I thought might be useful to someone else.  The code is as follows:

   1: public static class UrlExtensions
   2: {
   3:     public static string AbsoluteAction(this UrlHelper url, string action, string controller, object routeValues)
   4:     {
   5:         Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
   6:  
   7:         string absoluteAction = string.Format("{0}{1}",
   8:                                               requestUrl.GetLeftPart(UriPartial.Authority),
   9:                                               url.Action(action, controller, routeValues));
  10:  
  11:         return absoluteAction;
  12:     }
  13: }

Basically is takes the same values as Url.Action (or at least one of the Url.Action signatures) and adds the “left part” of the authority (see the MSDN Library GetLeftPart Docs).

So if you write the following code:

   1: Url.AbsoluteAction("Edit", "Users", new {id="username"});

You should get something like the following result if you are running it locally:

http://localhost:50717/Users/Edit/username

Enjoy!

Filed under: , , , ,

Comments

# re: A UrlHelper Extension For Creating Absolute Action Paths in ASP.NET MVC

Friday, October 16, 2009 3:45 PM by Robert

FYI:  Your project will need to reference System.Web.Abstractions and System.Web.Routing to get this to work.

# re: A UrlHelper Extension For Creating Absolute Action Paths in ASP.NET MVC

Wednesday, April 28, 2010 12:39 AM by Norman H Harebottle

Just exactly what I needed for implementing RPXNow.com authentication handling on my site.  Thanks!