ASP.NET: Getting the absolute url of a web page

Recently, I needed the way of getting the absolute URL of a web page in ASP.NET. With absolute URL, I mean the url what clients have to point to their browsers (this URL will be sent by mail), not the absolute URL relative to the web app, like the ASP.NET API seems to understand ‘absolute’.

I thought that there would be some method in the .NET Framework, but if it exists, I missed it. I looked at System.Web.VirtualPathUtility, System.IO.Path, System.Web.UI.Page and System.Web.HttpServerUtility, but no luck.

So I had to implement this. It is only a line of code, but I think that this can be useful for anyone else (including Future Me).

           String url = new Uri(Context.Request.Url, 
                            ResolveUrl("~/Example.aspx")).ToString();

If you’re using the development server Cassini, included with Visual Studio, it will return something similar to http://localhost:1234/Example.aspx. In production on IIS, it will return something like http://example.com/Example.aspx.

If you know a better way of getting the absolute URL from a page, feel free to leave a comment.

6 Responses

  1. No es el mejor post para hacerlo, pero el meme que te acabo de pasar obliga, tengo que comentarte. Beziz

  2. Thanks for all the information and for visiting my site.

  3. Would just using:

    Request.Url.ToString()

    get you all the information you need?

  4. Hi John!

    That’s a perfect solution if you’re looking for the url of the current page. But what I needed was the url of another page on my site.

  5. Great solution – works well – especially useful with master pages.

  6. Great, but where is the source code?

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: