在一次调用中Request.Url.Host和ApplicationPath
有没有办法在一次调用中获取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; }
这不能在我的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(或其他一些架构!)它的工作原理!
感谢所有的回复,但没有一个是我正在寻找的。 仅供参考,我以这种方式解决了问题(但我仍然有兴趣知道是否有更顺畅的方式):
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 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, "/")
HttpContext.Current.Request.Url.AbsoluteUri