在代码后台获取ASP.Net页面的URL

203

我有一个ASP.Net页面将在几个不同的服务器上托管,我想获取该页面的URL(或更好的是:托管页面的站点)作为字符串在代码后台中使用。 有什么建议吗?


请查看此解决方案:https://dev59.com/xHRB5IYBdhLWcg3wn4fc#567632 - Kimball Robinson
请参考以下链接中的详细回答:https://dev59.com/XXRB5IYBdhLWcg3wiHv7#16693496 - Learning
看到重复的链接真是有趣...在这个问题被提出的时候,Stack Overflow还不到一个月的时间。 - Joel Coehoorn
10个回答

237
使用这个:
Request.Url.AbsoluteUri

这会给你完整的路径(包括http://..)。


8
记住,这也包括查询部分(?key=value...)。 - Marcel
5
如果应用程序不是托管在服务器根目录而是在一个目录中,则此方法无法正常工作。如果应用程序托管在www.contoso.com/app/上,则此方法将仅返回www.contoso.com。 - linkerro

121

如果你只想要请求的 scheme 和 authority 部分(协议、主机和端口)使用:

Request.Url.GetLeftPart(UriPartial.Authority)

3
更好的解决方案已发布在https://dev59.com/xHRB5IYBdhLWcg3wn4fc。 - Kimball Robinson
25
@Kimball,我不确定将字符串拼接在一起是否是更好的解决方案。 - William

30
我正在使用
Request.Url.GetLeftPart(UriPartial.Authority) +
        VirtualPathUtility.ToAbsolute("~/")

13

我在自定义类中使用此代码。用于发送邮件非常方便,例如 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;
    }

}

如果你想在代码后端使用它,就不需要上下文。


2
请注意,Authority 不包括协议 (http://https://)。虽然在您的实例中可以正常工作,但对于某些情况可能不适用。可以通过 System.Web.HttpContext.Current.Request.Url.Scheme 获取。 - vapcguy

8
你需要服务器名还是主机名? Stephen提供了Request.Url.Host。
使用Dns.GetHostName可以获取服务器名称。 Request.Url可以访问有关所请求页面的大部分信息。请注意保留HTML标记。

7
Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + "?theme=blue";

这将为您提供当前页面的完整路径。我添加了查询字符串。


5

我也面临同样的问题,目前我发现:

new Uri(Request.Url,Request.ApplicationPath)

或者

Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath

3

Request.Url.Host


2
使用一个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>

2
如果您想在末尾包含任何类似于example.com?id=99999的唯一字符串,则请使用以下内容。
Dim rawUrl As String = Request.RawUrl.ToString()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接