有没有什么办法让HttpContext.Current.Request.Url.Host
和HttpContext.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; }
MartinHN.. 31
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; }
我已经在不同的网站上使用了这个多年 - 并且它为您提供了所请求的服务器名称,这是从http://到第一个/ (2认同)
Samuel.. 18
这不能在我的localhost上使用端口号进行修改:
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; }
Dan Diplo.. 6
你应该做的是:
return String.Format("{0}://{1}/", Request.Url.Scheme, Request.Url.Host);
这样,如果你使用HTTPS(或其他一些架构!)它的工作原理!
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; }
这不能在我的localhost上使用端口号进行修改:
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(或其他一些架构!)它的工作原理!