Get URL of ASP.Net Page in code-behind

I have an ASP.Net page that will be hosted on a couple different servers, and I want to get the URL of the page (or even better: the site where the page is hosted) as a string for use in the code-behind. Any ideas?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use this:

Request.Url.AbsoluteUri

That will get you the full path (including http://...)

Method 2

If you want only the scheme and authority part of the request (protocol, host and port) use

Request.Url.GetLeftPart(UriPartial.Authority)

Method 3

I am using

Request.Url.GetLeftPart(UriPartial.Authority) +
        VirtualPathUtility.ToAbsolute("~/")

Method 4

I use this in my code in a custom class. Comes in handy for sending out emails like [email protected]
[email protected]” + BaseSiteUrl
Works fine on any site.

// get a sites base urll ex: example.com
public static string BaseSiteUrl
{
    get
    {
        HttpContext context = HttpContext.Current;
        string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');
        return baseUrl;
    }

}

If you want to use it in codebehind get rid of context.

Method 5

Do you want the server name? Or the host name?

Request.Url.Host ala Stephen

Dns.GetHostName – Server name

Request.Url will have access to most everything you’ll need to know about the page being requested.

Method 6

Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + "?theme=blue";

that will give you the full path to the page you are sitting on. I added in the querystring.

Method 7

I’m facing same problem and so far I found:

new Uri(Request.Url,Request.ApplicationPath)

or

Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath

Method 8

Request.Url.Host

Method 9

If you want to include any unique string on the end, similar to example.com?id=99999, then use the following

Dim rawUrl As String = Request.RawUrl.ToString()

Method 10

Using a js file you can capture the following, that can be used in the codebehind as well:

<script type="text/javascript">
    alert('Server: ' + window.location.hostname);
    alert('Full path: ' + window.location.href);
    alert('Virtual path: ' + window.location.pathname);
    alert('HTTP path: ' + 
        window.location.href.replace(window.location.pathname, ''));    
</script>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x