加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何获取网站根URL?

发布时间:2020-12-15 19:08:27 所属栏目:asp.Net 来源:网络整理
导读:我想动态获取ASP.NET应用程序的绝对根Url。这需要是以下形式的应用程序的完整根网址:http(s):// hostname(:port)/ 我一直在使用这个静态方法: public static string GetSiteRootUrl(){ string protocol; if (HttpContext.Current.Request.IsSecureConnec
我想动态获取ASP.NET应用程序的绝对根Url。这需要是以下形式的应用程序的完整根网址:http(s):// hostname(:port)/

我一直在使用这个静态方法:

public static string GetSiteRootUrl()
{
    string protocol;

    if (HttpContext.Current.Request.IsSecureConnection)
        protocol = "https";
    else
        protocol = "http";

    StringBuilder uri = new StringBuilder(protocol + "://");

    string hostname = HttpContext.Current.Request.Url.Host;

    uri.Append(hostname);

    int port = HttpContext.Current.Request.Url.Port;

    if (port != 80 && port != 443)
    {
        uri.Append(":");
        uri.Append(port.ToString());
    }

    return uri.ToString();
}

但是,如果我没有HttpContext.Current在范围内?
我在CacheItemRemovedCallback中遇到了这种情况。

解决方法

对于WebForms,此代码将返回应用程序根目录的绝对路径,无论应用程序嵌套的方式如何:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")

上面的第一部分返回没有尾部斜杠的应用程序(http:// localhost)的方案和域名。 ResolveUrl代码返回应用程序根目录(/ MyApplicationRoot /)的相对路径。通过将它们组合在一起,您可以获得Web表单应用程序的绝对路径。

使用MVC:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")

或者,如果您尝试直接在Razor视图中使用它:

@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读