假设我正在主持一个网站http://www.foobar.com。如何获取ASP.NET中的根域URI?
有没有一种方法可以在我的代码后面以编程方式确定“http://www.foobar.com/”(即不必在我的web配置中对其进行硬编码)?
假设我正在主持一个网站http://www.foobar.com。如何获取ASP.NET中的根域URI?
有没有一种方法可以在我的代码后面以编程方式确定“http://www.foobar.com/”(即不必在我的web配置中对其进行硬编码)?
HttpContext.Current.Request.Url可以让你得到关于URL的所有信息。并可以将网址分解成碎片。
为了让整个请求URL字符串:
HttpContext.Current.Request.Url
为了获得请求的www.foo.com部分:
HttpContext.Current.Request.Url.Host
需要注意的是,在一定程度上,在你的ASP.NET应用程序之外的因素的怜悯。如果IIS配置为接受您的应用程序的多个主机头或任何主机头,则通过DNS解析到应用程序的任何域都可能显示为请求URL,具体取决于用户输入的内容。
string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"
C#下例:
string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();
string domainName = Request.Url.Host
对任何人来说仍然不知道,一个更完整的答案,请http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/。
public string FullyQualifiedApplicationPath
{
get
{
//Return variable declaration
var appPath = string.Empty;
//Getting the current context of HTTP request
var context = HttpContext.Current;
//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
context.Request.Url.Port == 80
? string.Empty
: ":" + context.Request.Url.Port,
context.Request.ApplicationPath);
}
if (!appPath.EndsWith("/"))
appPath += "/";
return appPath;
}
}
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
的GetLeftPart方法返回包含URI字符串的最左侧部分的字符串,由部分所指定的部分结束。
的方案和权威的URI的分段。
string host = Request.Url.Host;
Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
HttpCookie cookie = new HttpCookie(cookieName, "true");
if (domainReg.IsMatch(host))
{
cookieDomain = domainReg.Match(host).Groups[1].Value;
}
我知道这是旧的,但要做到这一点,正确的方法是现在
string Domain = HttpContext.Current.Request.Url.Authority
这将让与港口的DNS或IP地址的服务器。
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;
host.com =>返回host.com
s.host.com =>返回host.com
host.co.uk =>返回host.co.uk
万维网。 host.co.uk =>返回host.co.uk
s1.www.host.co.uk =>返回host.co.uk
这将特别返回您要求的内容。
Dim mySiteUrl = Request.Url.Host.ToString()
我知道这是一个老问题。但是我需要相同的简单答案,并且这正好返回了所要求的内容(没有http://)。
这工作也:
字符串URL = HttpContext.Request.Url.Authority;
如果例如链接http://www.foobar.com/Page1
HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
HttpContext.Current.Request.Url.Host; //returns "foobar.com"
HttpContext.Current.Request.Url.Scheme; //returns "http/https"
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
- 增加的端口上运行IIS快递
Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port
时由于依赖于请求帮助,你可以尝试寻找在`请求对象。 – 2009-07-31 20:11:30