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?
-
See this solution: stackoverflow.com/questions/567590/…– Kimball RobinsonSep 4, 2010 at 0:34
-
detailed answer here stackoverflow.com/questions/593709/…– LearningApr 26, 2015 at 4:12
-
It's funny to see the duplicate links... at the time this was question was asked Stack Overflow was still less than a month old.– Joel CoehoornNov 3, 2021 at 17:34
10 Answers
-
8
-
5This doesn't work if the application is not hosted on the server root but in a directory. If the application is hosted on www.contoso.com/app/ this will return just www.contoso.com– linkerroOct 3, 2012 at 8:58
If you want only the scheme and authority part of the request (protocol, host and port) use
Request.Url.GetLeftPart(UriPartial.Authority)
-
3An even better solution is posted at stackoverflow.com/questions/567590/… Sep 4, 2010 at 0:33
-
25@Kimball I'm not sure concatenating strings together is a better solution.– WilliamMar 27, 2011 at 11:10
I am using
Request.Url.GetLeftPart(UriPartial.Authority) +
VirtualPathUtility.ToAbsolute("~/")
I use this in my code in a custom class. Comes in handy for sending out emails like [email protected] "no-reply@" + 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.
-
2Note that
Authoritydoesn't include the protocol (http://orhttps://). Was fine in your instance but might not be for some. Can be obtained throughSystem.Web.HttpContext.Current.Request.Url.Scheme, though.– vapcguyDec 4, 2018 at 16:44
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.
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.
I'm facing same problem and so far I found:
new Uri(Request.Url,Request.ApplicationPath)
or
Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath
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()
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>