有没有什么办法让HttpContext.Current.Request.Url.HostHttpContext.Current.Request.ApplicationPath在一个电话?

像 “完整的应用程序的URL”?

编辑:澄清 - 我所需要的,这是[]中的部分:

http://[www.mysite.com/mywebapp]/Pages/Default.aspx

请问只是出于好奇。

编辑2:感谢所有的答复,但他们都不是正是我一直在寻找。 仅供参考,我的问题解决了这样的(但我还是想知道,如果有一个平滑的方式):

public string GetWebAppRoot()
{
    if(HttpContext.Current.Request.ApplicationPath == "/")
        return "http://" + HttpContext.Current.Request.Url.Host;
    else
        return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
}
有帮助吗?

解决方案

public static string GetSiteRoot()
{
  string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
  if (port == null || port == "80" || port == "443")
    port = "";
  else
    port = ":" + port;

  string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
  if (protocol == null || protocol == "0")
    protocol = "http://";
  else
    protocol = "https://";

  string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;

  if (sOut.EndsWith("/"))
  {
    sOut = sOut.Substring(0, sOut.Length - 1);
  }

  return sOut;
}

其他提示

这是不工作在我的本地与端口号,以便作出微小修改:

  private string GetWebAppRoot()
    {
        string host = (HttpContext.Current.Request.Url.IsDefaultPort) ? 
            HttpContext.Current.Request.Url.Host : 
            HttpContext.Current.Request.Url.Authority;
        host = String.Format("{0}://{1}", HttpContext.Current.Request.Url.Scheme, host);            
        if (HttpContext.Current.Request.ApplicationPath == "/")
            return host;
        else
            return host + HttpContext.Current.Request.ApplicationPath;
    }

什么你应该做的是:

return String.Format("{0}://{1}/", Request.Url.Scheme, Request.Url.Host);

,如果你使用的是HTTPS这样工作(或其他模式!)

感谢所有的答复,但他们都不是正是我一直在寻找。 仅供参考,我的问题解决了这样的(但我还是想知道,如果有一个平滑的方式):

public string GetWebAppRoot()
{
    if(HttpContext.Current.Request.ApplicationPath == "/")
        return "http://" + HttpContext.Current.Request.Url.Host;
    else
        return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
}
HttpContext.Current.Request.Url.AbsoluteUri
scroll top