Request.Url.Host и ApplicationPath в одном вызове
-
22-08-2019 - |
Вопрос
Есть ли способ получить 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;
}
Другие советы
Это не работало на моем локальном хосте с номером порта, поэтому внесены незначительные изменения:
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