كيف يمكنني حل مسارات تطبيق ASP.NET "~" إلى جذر موقع الويب دون وجود تحكم؟

StackOverflow https://stackoverflow.com/questions/2589542

  •  25-09-2019
  •  | 
  •  

سؤال

أرغب في حل "~/anhing" من السياقات غير الداخلية مثل Global.asax (httpapplication) ، httpmodule ، httphandler ، إلخ. ولكن يمكن فقط العثور على طرق الدقة هذه خاصة بعناصر التحكم (والصفحة).

أعتقد أن التطبيق يجب أن يكون لديه معرفة كافية ليكون قادرًا على تعيين هذا خارج سياق الصفحة. لا؟ أو على الأقل من المنطقي بالنسبة لي ، يجب حلها في ظروف أخرى ، أينما كان جذر التطبيق معروفًا.

تحديث: السبب في أنني أتمسك بالمسارات "~" في ملفات web.configuration ، وأريد حلها من السيناريوهات غير المذكورة أعلاه.

تحديث 2: أحاول حلها إلى جذر موقع الويب مثل Control.Resolve (..) سلوك عنوان URL ، وليس إلى مسار نظام الملفات.

هل كانت مفيدة؟

المحلول

هذا هو الجواب: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;
    }
}

لم أخبّر هذا المصاص ، لكنني أرميها هناك كحل يدوي لعدم العثور على طريقة حل في إطار .NET خارج السيطرة.

هذا عمل على "~/أيا كان" بالنسبة لي.

/// <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 بدون "~".

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top