如何获取站点根URL?

sai*_*lle 44 asp.net

我想动态获取ASP.NET应用程序的绝对根URL.这需要是以下形式的应用程序的完整根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();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我没有HttpContext.Current范围怎么办?我遇到过这样的情况CacheItemRemovedCallback.

sal*_*uce 77

对于WebForms,此代码将返回应用程序根目录的绝对路径,而不管应用程序的嵌套方式如何:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")
Run Code Online (Sandbox Code Playgroud)

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

使用MVC:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")
Run Code Online (Sandbox Code Playgroud)

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

@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")
Run Code Online (Sandbox Code Playgroud)

  • 如果您没有可用于调用`ResolveUrl`的ASP.NET页面,请参阅[此答案](http://stackoverflow.com/questions/4893380/resolveurl-without-an-asp-net-page). (2认同)

Jon*_*ood 26

您可以尝试获取原始URL并在前进斜杠之后修剪所有内容.你也可以加入ResolveUrl("~/").


Den*_*cob 11

public static string GetAppUrl()
{
    // This code is tested to work on all environments
    var oRequest = System.Web.HttpContext.Current.Request;
    return oRequest.Url.GetLeftPart(System.UriPartial.Authority)
        + System.Web.VirtualPathUtility.ToAbsolute("~/");

}
Run Code Online (Sandbox Code Playgroud)


小智 6

public static string GetFullRootUrl()
{   
    HttpRequest request = HttpContext.Current.Request;
    return request.Url.AbsoluteUri.Replace(request.Url.AbsolutePath, String.Empty);
}
Run Code Online (Sandbox Code Playgroud)


sai*_*lle 3

我通过在 AppSettings(“SiteRootUrl”)中添加 web.config 设置解决了这个问题。简单而有效,但需要维护另一个配置设置。

  • 你可以说我是一个逆向投资者,但我发现这是一个简单、优雅的解决方案,而且高度可移植且易于维护。我宁愿有一个单一的设置来跟踪,也不愿负责这个问题的答案中其他地方建议的大量代码。 (5认同)
  • 如果您必须移动站点,这并不能真正宣传自己是一个好方法。诚然,搬家是一件罕见的事情……但您可能会忘记这个小“宝石”,并且您的网站在新位置将完全崩溃。 (2认同)
  • 我可以说我已经在许多应用程序中使用这种技术一段时间了,没有产生任何不良影响。当我们转移到不同的环境时,我们总是必须直观地扫描配置文件,并且更改既明显又微不足道。 (2认同)
  • 这是唯一对我们有用的解决方案。如果 url 主机是 abc.example.com,我们需要识别根域“example.com”,但如果 url 是 test.example.com 或 abc.test.example.com,则需要识别“test.example.com”。如果没有硬编码值,根本不可能从请求 URL 中确定这一点。我努力避免需要配置设置,但最终这似乎是最简单的解决方案。 (2认同)