【发布时间】:2010-09-10 21:29:16
【问题描述】:
我有一个 ASP.Net 页面,它将托管在几个不同的服务器上,我想获取页面的 URL(或者更好的是:托管页面的站点)作为字符串用于代码隐藏。有什么想法吗?
【问题讨论】:
-
看到重复的链接很有趣...当时有人问这个问题 Stack Overflow 还不到一个月。
标签: asp.net
我有一个 ASP.Net 页面,它将托管在几个不同的服务器上,我想获取页面的 URL(或者更好的是:托管页面的站点)作为字符串用于代码隐藏。有什么想法吗?
【问题讨论】:
标签: asp.net
【讨论】:
如果您只想要请求的方案和权限部分(协议、主机和端口),请使用
Request.Url.GetLeftPart(UriPartial.Authority)
【讨论】:
我正在使用
Request.Url.GetLeftPart(UriPartial.Authority) +
VirtualPathUtility.ToAbsolute("~/")
【讨论】:
我在自定义类的代码中使用它。派上用场发送电子邮件,如 no-reply@example.com “无回复@” + BaseSiteUrl 在任何网站上都可以正常工作。
// 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;
}
}
如果您想在代码隐藏中使用它,请摆脱上下文。
【讨论】:
Authority 不包括协议(http:// 或 https://)。在您的情况下很好,但可能不适用于某些人。不过可以通过System.Web.HttpContext.Current.Request.Url.Scheme获得。
【讨论】:
Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + "?theme=blue";
这将为您提供您所在页面的完整路径。我在查询字符串中添加了。
【讨论】:
我遇到了同样的问题,到目前为止我发现:
new Uri(Request.Url,Request.ApplicationPath)
或
Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath
【讨论】:
Request.Url.Host
【讨论】:
如果您想在末尾包含任何唯一字符串,类似于 example.com?id=99999,请使用以下内容
Dim rawUrl As String = Request.RawUrl.ToString()
【讨论】:
使用 js 文件,您可以捕获以下内容,也可以在代码隐藏中使用:
<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>
【讨论】: