Sunday, October 30, 2011

How to get web site url in asp.net


When you want to get one web site url such as http://www.iblogseeker.com/register.aspx, use the following code:
 
public string GetSiteUrl()
{
string baseUrl = null;
HttpContext c = HttpContext.Current;
if (c != null)
{
string port = c.Request.ServerVariables["SERVER_PORT"];
if (port == null || port.Equals("80") || port.Equals("443"))
port = String.Empty;
else
port = ":" + port;
string protocol = c.Request.ServerVariables["SERVER_PORT_SECURE"];
if (protocol == null || protocol.Equals("0"))
protocol = "http://";
else
protocol = "https://";
baseUrl = protocol + c.Request.ServerVariables["SERVER_NAME"] + port + c.Request.ApplicationPath;
}
return baseUrl;
}

It covers any url in active on web.

1 comment:

  1. I think Request.Url is also useful as well.
    http://goo.gl/7s4Kz

    Uri class contains a lot of information about, well, url. :)
    http://goo.gl/OAxrS

    ReplyDelete