ASP.NET MVC Tip # 3 – Getting an Absolute Url Using an Extension Method

Thursday, February 7, 2008

This is probably a good time to note… all of this is based on a CTP version of the MVC framework.  I’m putting this together mostly as a reference for myself.  If you start developing with any of these tips, new versions of the MVC framework will have a lot of this built in, and may even break some of your code.  Just a warning…


Scenario:


Part of my application requires that all new users verify their email address.  To accomplish this, the application will send an email with a verification link to the email address provided by the user.  In the email, the user needs the absolute url to verify her email address.  How do we get the absolute Url of a ASP.NET MVC route? 


Solution:


The RouteCollection object has a helpful method for getting a string representation of the Url:  GetUrl(RequestContext context, object values);


The drawback to this method is that it returns only the relative path to the desired action.  In order to get the absolute path, I created a simple extension method which extends the RouteCollection class with a new method GetAbsoluteUrl.  This method also allows us to pass in the protocol to use for the absolute path.  This is helpful if we want to send the user to a SSL secured page.



You can now use this from your controller by specifying the required values.




Again, please keep in mind that all of this is based on a CTP release of the MVC framework and future releases will likely be cause this to be redundant at best or break your entire MVC application at worst :-)

2 Comments

  1. http:// says:

    Thanks for sharing

  2. http:// says:

    Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl(“~/Page.aspx”)

Leave a Reply