微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我想动态获取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("~/")

原文地址:https://www.jb51.cc/aspnet/254404.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐