18

有什么方法可以HttpContext.Current.Request.Url.Host一键HttpContext.Current.Request.ApplicationPath通话吗?

像“完整的应用程序网址”之类的东西?

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

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;
}
4

6 回答 6

32
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;
}
于 2009-03-27T14:06:56.390 回答
18

这不适用于带有端口号的本地主机,因此进行了较小的修改:

  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;
    }
于 2009-09-28T01:53:41.553 回答
7

你真正应该做的是:

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

如果您使用的是 HTTPS(或其他模式!)

于 2009-08-19T13:46:35.097 回答
3

感谢所有回复,但没有一个是我想要的。仅供参考,我以这种方式解决了问题(但我仍然想知道是否有更顺畅的方式):

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;
}
于 2009-03-30T16:06:26.017 回答
2

检查这篇文章

public static Uri GetBaseUrl(HttpRequest request)
{
    Uri contextUri = new Uri(request.Url, request.RawUrl);
    UriBuilder realmUri = new UriBuilder(contextUri) { Path = request.ApplicationPath, Query = null, Fragment = null };
    return realmUri.Uri;
}

public static string GetAbsoluteUrl(HttpRequest request, string relativeUrl)
{
    return new Uri(GetBaseUrl(request), VirtualPathUtility.ToAbsolute(relativeUrl)).AbsoluteUri;
}

如果你没有直接从 GetBaseUrl 得到你需要的东西,应该可以这样做:

GetAbsoluteUrl(HttpContext.Current.Request, "/")

于 2009-03-27T13:10:37.867 回答
1
HttpContext.Current.Request.Url.AbsoluteUri
于 2009-03-27T13:11:05.870 回答