2010-04-07 1 views
13

Global.asax (HttpApplication), HttpModule, HttpHandler 등과 같은 비 페이지 컨텍스트에서 "~/whatever"를 해결하려고하지만 컨트롤 (및 Page)과 관련된 특정 해결 방법 만 찾을 수 있습니다.컨트롤이없는 상태에서 웹 사이트 루트에 대한 ASP.NET 경로를 확인할 수 있습니까?

나는 앱이 페이지 컨텍스트 외부에서 이것을 매핑 할 수있는 충분한 지식을 가지고 있어야한다고 생각한다. 아니? 또는 적어도 응용 프로그램 루트가 알려진 모든 다른 상황에서 해결되어야한다는 것은 나에게 의미가 있습니다.

업데이트 : 이유는 web.configuration 파일에 "~"경로를 지정하고 전술 한 비 제어 시나리오에서 해결하려고하기 때문입니다.

업데이트 2 : 파일 시스템 경로가 아닌 Control.Resolve (..) URL 동작과 같은 웹 사이트 루트를 해결하려고합니다.

+0

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

답변

1

사용자가 직접 HttpContext.Current 개체에 액세스하여이를 수행 할 수 있습니다주의해야 할

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

한 점은 HttpContext.Current은 실제 요구의 맥락에서 null 비 될 것입니다 점이다. 예를 들어 Application_Stop 이벤트에서는 사용할 수 없습니다.

+3

파일 시스템이 아니라 URL로 해석하려고하기 때문에 질문을 업데이트했습니다. –

0

나는이 빠는 사람을 디버깅하지 않았지만 Control 외부의 .NET Framework에서 Resolve 메서드를 찾을 수 없다는 수동 솔루션으로 던졌습니다.

이것은 "~/뭐든간에"나를 위해 작동했습니다.

/// <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

같은 질문에 대한 답 2 점이 무엇입니까? –

0

, System.AppDomain.BaseDirectory를 사용해보십시오. 웹 사이트의 경우 웹 사이트의 루트 여야합니다. 그런 다음 System.IO.Path.Combine을 "~"없이 MapPath에 전달할 항목으로 수행하십시오. Global.asax에 추가에서

1

다음

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; 
    } 
} 
관련 문제