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!

2 Comments

Comments have been disabled for this content.