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:
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:
You should get something like the following result if you are running it locally: