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.
Filed under: Coding, Tech | Tagged: .NET Technology, absolute url, ASP.NET |
No es el mejor post para hacerlo, pero el meme que te acabo de pasar obliga, tengo que comentarte. Beziz
Thanks for all the information and for visiting my site.
Would just using:
Request.Url.ToString()
get you all the information you need?
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.
Great solution – works well – especially useful with master pages.
Great, but where is the source code?