比方说,我在主持一个网站http://www.foobar.com 。
有没有一种方法,我可以以编程方式确定“ http://www.foobar.com/在我的代码”的背后(即不必硬编码在我的web配置)?
比方说,我在主持一个网站http://www.foobar.com 。
有没有一种方法,我可以以编程方式确定“ http://www.foobar.com/在我的代码”的背后(即不必硬编码在我的web配置)?
HttpContext.Current.Request.Url可以让你的所有URL上的信息。 并且可以分解成URL的片段。
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
乌里:: GetLeftPart方法 :
该方法GetLeftPart返回包含URI字符串的最左侧部分的字符串,由部分所指定的部分结束。
UriPartial枚举 :
URI的方案和权威段。
对于任何人仍然不知道,一个更完整的答案,请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 hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"
如果例如链接http://www.foobar.com/Page1
HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"
HttpContext.Current.Request.Url.Scheme; //returns "http/https"
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
为了让整个请求URL字符串:
HttpContext.Current.Request.Url
为了得到要求的www.foo.com部分:
HttpContext.Current.Request.Url.Host
请注意,您是,在一定程度上,在你的ASP.NET应用程序的外部因素的摆布。 如果IIS配置为接受多个或任何主机头为您的应用程序,那么任何其决心通过DNS应用程序的域可能会显示为请求的URL,根据用户输入的是哪一个。
运行IIS快递的时候 - 增加的端口可以帮助
Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port
string domainName = Request.Url.Host
我知道这是旧的,但现在要做到这一点,正确的做法是
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
www.host.co.uk =>返回host.co.uk
s1.www.host.co.uk =>返回host.co.uk
这个作品也:
串URL = HttpContext.Request.Url.Authority;
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 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;
}
确切地说,这将返回你所要求的。
Dim mySiteUrl = Request.Url.Host.ToString()
我知道这是一个老问题。 但我需要同样的答案很简单,这返回到底是什么要求(没有http://)。