假设我在http://www.foobar.com上托管了一个网站.
有没有办法可以在我的代码中以编程方式确定" http://www.foobar.com/ "(即无需在我的Web配置中对其进行硬编码)?
Geo*_*rge 162
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
Run Code Online (Sandbox Code Playgroud)
GetLeftPart方法返回一个字符串,其中包含URI字符串的最左边部分,以part指定的部分结束.
URI的方案和权限段.
Bri*_*den 122
对于仍然想知道的人,可以在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;
}
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*rke 80
HttpContext.Current.Request.Url可以获取有关URL的所有信息.并且可以将url分解成碎片.
Ben*_*esh 27
string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"
Run Code Online (Sandbox Code Playgroud)
Dhe*_*iri 27
如果示例Url是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"
Run Code Online (Sandbox Code Playgroud)
Rex*_*x M 16
要获取整个请求URL字符串:
HttpContext.Current.Request.Url
Run Code Online (Sandbox Code Playgroud)
要获得请求的www.foo.com部分:
HttpContext.Current.Request.Url.Host
Run Code Online (Sandbox Code Playgroud)
请注意,您在某种程度上受ASP.NET应用程序之外的因素的影响.如果IIS配置为接受应用程序的多个或任何主机标头,那么通过DNS解析到您的应用程序的任何域可能会显示为请求URL,具体取决于用户输入的那个.
小智 5
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;
Run Code Online (Sandbox Code Playgroud)
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
归档时间: |
|
查看次数: |
164767 次 |
最近记录: |