[英]Request.Url.Host and ApplicationPath in one call
有沒有辦法在一次調用中獲取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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.