如何在没有Control存在的情况下解析ASP.NET“〜”应用程序路径到网站根目录?

时间:2010-04-07 01:57:44

标签: asp.net-2.0 resolveurl

我想从非页面上下文中解析“〜/ whatever”,例如Global.asax(HttpApplication),HttpModule,HttpHandler等,但只能找到特定于Controls(和Page)的解析方法。

我认为该应用应该具有足够的知识,能够在页面上下文之外映射。没有?或者至少它对我有意义,它应该在其他情况下,只要知道应用程序根目录就可以解析。

更新:原因是我在web.configuration文件中粘贴了“〜”路径,并希望从上述非控制方案中解决它们。

更新2:我正在尝试将它们解析为网站根目录,例如Control.Resolve(..)网址行为,而不是文件系统路径。

6 个答案:

答案 0 :(得分:34)

这是答案: ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function

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

答案 1 :(得分:1)

您可以直接访问HttpContext.Current对象:

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

需要注意的一点是,HttpContext.Current在实际请求的上下文中只是非null。例如,它在Application_Stop事件中不可用。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

我没有调试过这个傻瓜,但我把它当作手动解决方案,因为在.NET框架之外的.NET框架中找不到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;
}

答案 4 :(得分: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));
}

答案 5 :(得分:0)

请尝试使用System.AppDomain.BaseDirectory,而不是使用MapPath。对于网站,这应该是您网站的根。然后使用你要传递给MapPath而不使用“〜”的任何内容来执行System.IO.Path.Combine。