有没有办法在一次调用中获取 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;
}
最佳答案
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;
}
关于c# - Request.Url.Host 和 ApplicationPath 一次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/689678/