Как я могу разрешить ASP.NET "~" пути приложения к корню сайта без присутствия элемента управления? - PullRequest
14 голосов
/ 07 апреля 2010

Я хочу разрешить "~ / what" изнутри нестраничных контекстов, таких как Global.asax (HttpApplication), HttpModule, HttpHandler и т. Д., Но могу найти только такие методы разрешения, специфичные для элементов управления (и Page).

Я думаю, что приложение должно иметь достаточно знаний, чтобы отобразить это вне контекста страницы. Нет? Или, по крайней мере, для меня имеет смысл, что это должно быть разрешено в других обстоятельствах, где бы ни был известен корень приложения.

Обновление : причина в том, что я втыкаю "~" пути в файлы web.configuration и хочу разрешить их в вышеупомянутых сценариях без контроля.

Обновление 2: Я пытаюсь разрешить их в корне сайта, например в поведении URL Control.Resolve (..), а не в пути к файловой системе.

Ответы [ 6 ]

34 голосов
/ 07 апреля 2010

Вот ответ: ASP.Net: Использование System.Web.UI.Control.ResolveUrl () в общей / статической функции

string absoluteUrl = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");
1 голос
/ 18 февраля 2013

В 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;
    }
}
1 голос
/ 07 апреля 2010

Вы можете сделать это, обратившись к объекту HttpContext.Current напрямую:

var resolved = HttpContext.Current.Server.MapPath("~/whatever")

Следует отметить, что HttpContext.Current будет не только -1006 * в контекстеактуальный запрос.Например, он недоступен в событии Application_Stop.

0 голосов
/ 07 апреля 2010

Вместо использования MapPath, попробуйте использовать System.AppDomain.BaseDirectory. Для сайта это должен быть корень вашего сайта. Затем выполните System.IO.Path.Combine с тем, что вы собираетесь передать в MapPath без "~".

0 голосов
/ 07 апреля 2010
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));
}
0 голосов
/ 07 апреля 2010

Я не отлаживал этот присоски, но выкидываю его в качестве ручного решения из-за отсутствия поиска метода Resolve в .NET Framework вне Control.

Это сработало для меня "~ / что угодно".

/// <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;
}
...