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.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
If you know a better way of getting the absolute URL from a page, feel free to leave a comment.