Ответ 1
Вот ответ: ASP.Net: Использование System.Web.UI.Control.ResolveUrl() в общей/статической функции
string absoluteUrl = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");
Я хочу разрешить "~/whatever" из внутренних контекстов, отличных от страницы, таких как Global.asax(HttpApplication), HttpModule, HttpHandler и т.д., но может найти только такие методы разрешения, специфичные для элементов управления (и страницы).
Я думаю, что приложение должно обладать достаточными знаниями, чтобы иметь возможность отображать это вне контекста страницы. Нет? Или, по крайней мере, это имеет смысл для меня, он должен быть разрешен в других обстоятельствах, где известен корень приложения.
Обновить. Причина в том, что я придерживаюсь "~" путей в файлах web.configuration и хочу разрешить их из вышеупомянутых сценариев, отличных от Control.
Обновление 2: Я пытаюсь разрешить их для корневого сайта веб-сайта, такого как поведение Control.Resolve(..), а не путь к файловой системе.
Вот ответ: ASP.Net: Использование System.Web.UI.Control.ResolveUrl() в общей/статической функции
string absoluteUrl = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");
Вы можете сделать это, обратившись непосредственно к объекту HttpContext.Current
:
var resolved = HttpContext.Current.Server.MapPath("~/whatever")
Следует отметить, что HttpContext.Current
будет только не null
в контексте реального запроса. Например, он недоступен в событии Application_Stop
.
В Global.asax добавьте следующее:
private static string ServerPath { get; set; }
protected void Application_BeginRequest(Object sender, EventArgs e)
{
ServerPath = BaseSiteUrl;
}
protected static string BaseSiteUrl
{
get
{
var context = HttpContext.Current;
if (context.Request.ApplicationPath != null)
{
var baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
return baseUrl;
}
return string.Empty;
}
}
Я не отлаживал эту присоску, но бросаю ее туда как ручное решение из-за отсутствия поиска метода Resolve в .NET Framework вне Control.
Это работало над "~/whatever" для меня.
/// <summary>
/// Try to resolve a web path to the current website, including the special "~/" app path.
/// This method be used outside the context of a Control (aka Page).
/// </summary>
/// <param name="strWebpath">The path to try to resolve.</param>
/// <param name="strResultUrl">The stringified resolved url (upon success).</param>
/// <returns>true if resolution was successful in which case the out param contains a valid url, otherwise false</returns>
/// <remarks>
/// If a valid URL is given the same will be returned as a successful resolution.
/// </remarks>
///
static public bool TryResolveUrl(string strWebpath, out string strResultUrl) {
Uri uriMade = null;
Uri baseRequestUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority));
// Resolve "~" to app root;
// and create http://currentRequest.com/webroot/formerlyTildeStuff
if (strWebpath.StartsWith("~")) {
string strWebrootRelativePath = string.Format("{0}{1}",
HttpContext.Current.Request.ApplicationPath,
strWebpath.Substring(1));
if (Uri.TryCreate(baseRequestUri, strWebrootRelativePath, out uriMade)) {
strResultUrl = uriMade.ToString();
return true;
}
}
// or, maybe turn given "/stuff" into http://currentRequest.com/stuff
if (Uri.TryCreate(baseRequestUri, strWebpath, out uriMade)) {
strResultUrl = uriMade.ToString();
return true;
}
// or, maybe leave given valid "http://something.com/whatever" as itself
if (Uri.TryCreate(strWebpath, UriKind.RelativeOrAbsolute, out uriMade)) {
strResultUrl = uriMade.ToString();
return true;
}
// otherwise, fail elegantly by returning given path unaltered.
strResultUrl = strWebpath;
return false;
}
public static string ResolveUrl(string url)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException("url", "url can not be null or empty");
}
if (url[0] != '~')
{
return url;
}
string applicationPath = HttpContext.Current.Request.ApplicationPath;
if (url.Length == 1)
{
return applicationPath;
}
int startIndex = 1;
string str2 = (applicationPath.Length > 1) ? "/" : string.Empty;
if ((url[1] == '/') || (url[1] == '\\'))
{
startIndex = 2;
}
return (applicationPath + str2 + url.Substring(startIndex));
}
Вместо использования MapPath попробуйте использовать System.AppDomain.BaseDirectory. Для веб-сайта это должно быть корнем вашего сайта. Затем выполните System.IO.Path.Combine с тем, что вы собираетесь передать MapPath без "~".