如何获得相对uri的绝对uri?

时间:2011-04-06 14:47:21

标签: asp.net uri relative-path absolute-path

我有一个页面的相对路径为“〜/ pages / mypage.aspx”。

我尝试使用VirtualPathUtility.ToAbsolute(@“〜/ pages / mypage.aspx”)希望得到绝对的uri,但它只返回相同的相对路径。

我怎么能从这个相对的uri那里得到绝对的uri?

谢谢,

2 个答案:

答案 0 :(得分:2)

我使用了这种方法:

private static string GetAbsoluteUrl(string relativeUrl)
    {
        var applicationUrl = String.Empty;

        // remove ~
        if (relativeUrl.StartsWith("~"))
        {
            applicationUrl = relativeUrl.Substring(1);
        }

        applicationUrl = (HttpContext.Current.Request.ApplicationPath + applicationUrl)
            .Replace("//", "/");

        var baseUrl = String.Format("{0}://{1}:{2}",
                                    HttpContext.Current.Request.Url.Scheme,
                                    HttpContext.Current.Request.Url.Host,
                                    HttpContext.Current.Request.Url.Port);

        return baseUrl + applicationUrl;
    }

答案 1 :(得分:0)

 public static string ResolveUrl(string originalUrl)
    {
        if (originalUrl == null)
            return null;

        // *** Absolute path - just return
        if (originalUrl.IndexOf("://") != -1)
            return originalUrl;

        // *** Fix up image path for ~ root app dir directory
        if (originalUrl.StartsWith("~"))
        {
            string newUrl = "";
            if (HttpContext.Current != null)
                newUrl = HttpContext.Current.Request.ApplicationPath +
                      originalUrl.Substring(1).Replace("//", "/");
            else
                // *** Not context: assume current directory is the base directory
                throw new ArgumentException("Invalid URL: Relative URL not allowed.");

            // *** Just to be sure fix up any double slashes
            return newUrl;
        }

        return originalUrl;
    }

取自http://www.west-wind.com/weblog/posts/154812.aspx