我有一个ASP.Net页面将在几个不同的服务器上托管,我想获取该页面的URL(或更好的是:托管页面的站点)作为字符串在代码后台中使用。 有什么建议吗?
我有一个ASP.Net页面将在几个不同的服务器上托管,我想获取该页面的URL(或更好的是:托管页面的站点)作为字符串在代码后台中使用。 有什么建议吗?
Request.Url.AbsoluteUri
这会给你完整的路径(包括http://..)。
如果你只想要请求的 scheme 和 authority 部分(协议、主机和端口)使用:
Request.Url.GetLeftPart(UriPartial.Authority)
Request.Url.GetLeftPart(UriPartial.Authority) +
VirtualPathUtility.ToAbsolute("~/")
我在自定义类中使用此代码。用于发送邮件非常方便,例如 no-reply@example.com "no-reply@" + 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
获取。 - vapcguyRequest.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + "?theme=blue";
这将为您提供当前页面的完整路径。我添加了查询字符串。
我也面临同样的问题,目前我发现:
new Uri(Request.Url,Request.ApplicationPath)
或者
Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath
Request.Url.Host
<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>
Dim rawUrl As String = Request.RawUrl.ToString()