Wie kann ich ASP.NET „~“ App Pfade auf der Website root ohne Kontrolle anwesend lösen?

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

  •  25-09-2019
  •  | 
  •  

Frage

Ich möchte Resolve „~ / was auch immer“ von innen nicht-Seite Kontexten wie Global.asax (Httpapplication), Httpmodule, Httphandler, usw., sondern nur solche Resolution Methoden spezifisch für Controls (und Seite) finden.

Ich denke, die App genug Kenntnisse, um diese außerhalb der Lage sein sollte, die Seitenkontext abzubilden. Nein? Oder zumindest macht es Sinn für mich sollte es unter anderen Umständen auflösbar sein, wo die App Wurzel bekannt ist.

Aktualisieren . Der Grund dafür ist ich bleibe „~“ Wege in den web.configuration-Dateien und will, dass sie aus den oben genannten nicht-Control-Szenarien lösen

Update. 2: Ich versuche, sie auf die Website Wurzel zu lösen wie Control.Resolve (..) URL Verhalten, nicht auf eine Dateisystempfad

War es hilfreich?

Lösung

Hier ist die Antwort: ASP.Net: Verwenden des Systems .Web.UI.Control.ResolveUrl () in einer gemeinsamen / statischen Funktion

string absoluteUrl = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");

Andere Tipps

Sie können es tun, indem Zugriff auf das HttpContext.Current Objekt direkt:

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

Ein Punkt zu beachten ist, dass, HttpContext.Current nur nicht-null im Rahmen einer tatsächlichen Anforderung sein wird. Es ist nicht im Application_Stop Ereignisse, zum Beispiel.

hinzufügen In Global.asax Folgendes:

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

Ich habe diesen Sauger nicht debuggt, aber ich warf es unsere dort als manuelle Lösung mangels einer Resolve-Methode in .NET Framework außerhalb der Kontrolle zu finden.

Das hat die Arbeit an einem "~ / was auch immer" für mich.

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

Statt MapPath zu verwenden, versuchen System.AppDomain.BaseDirectory verwenden. Für eine Website, sollte dies die Wurzel Ihrer Website. Dann machen Sie eine System.IO.Path.Combine mit dem, was Sie zu MapPath ohne die „~“ passieren würden.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top