1回の呼び出しでRequest.Url.HostとApplicationPath
-
22-08-2019 - |
質問
1回の呼び出しでHttpContext.Current.Request.Url.Host
とHttpContext.Current.Request.ApplicationPath
を取得する方法はありますか?
"完全なアプリケーションのURL" のようなもの?
編集:明確化 - 私は必要なもの、これは[]内の一部であります:
http://[www.mysite.com/mywebapp]/Pages/Default.aspx
私は好奇心だけでお願いします。
EDIT 2:すべての回答のおかげで、それらのどれもが私が探していたまさにでした。 FYI、私はこの問題をこのように解決し(ただし、スムーズな方法がありますかどうかを知るにはまだ興味を持っています):
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を使用している場合、それが動作する方法(またはいくつかの他のスキーマを!)
すべての返信のおかげで、それらのどれも私が探していたまさにでした。 FYI、私はこの問題をこのように解決し(ただし、スムーズな方法がありますかどうかを知るにはまだ興味を持っています):
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
所属していません StackOverflow