2010-04-07 10 views
13

Voglio risolvere "~/qualsiasi cosa" da contesti non-page come Global.asax (HttpApplication), HttpModule, HttpHandler, ecc. Ma è possibile trovare solo metodi di risoluzione specifici per Controls (e Page).Come posso risolvere i percorsi delle app "~" di ASP.NET alla radice del sito Web senza che sia presente un controllo?

Penso che l'app dovrebbe avere abbastanza conoscenze per essere in grado di mappare questo fuori dal contesto della pagina. No? O almeno ha senso per me dovrebbe essere risolvibile in altre circostanze, ovunque sia nota la radice dell'app.

Aggiornamento: Il motivo è che sto attaccando "~" percorsi nei file web.configuration, e vuole risolverli dai summenzionati scenari non di controllo.

Aggiornamento 2: Sto cercando di risolverli sul sito Web root come Control.Resolve (..) comportamento dell'URL, non su un percorso del file system.

+0

duplicato: http://stackoverflow.com/questions/26796/asp-net-using-system-web-ui-control-resolveurl-in- a-shared-static-function –

risposta

1

È possibile farlo accedendo direttamente l'oggetto HttpContext.Current:

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

Un punto da notare è che, HttpContext.Current è solo andare a essere non null nel contesto di una richiesta effettiva. Ad esempio, non è disponibile nell'evento Application_Stop.

+3

Ho aggiornato la domanda perché sto cercando di risolvere un URL, non il file system. –

0

Non ho eseguito il debug di questo pollone ma lo lancio come soluzione manuale per la mancanza di trovare un metodo Resolve in .NET Framework al di fuori di Control.

Questo ha funzionato su un "~/qualsiasi cosa" per me.

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

Qual è il punto delle risposte del post 2 per la stessa domanda? –

0

Invece di usare MapPath, provare a utilizzare System.AppDomain.BaseDirectory. Per un sito Web, questa dovrebbe essere la radice del tuo sito web. Quindi fai un System.IO.Path.Combine con quello che vuoi passare a MapPath senza "~".

1

In Global.asax aggiungere il seguente:

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