【问题标题】:How to get the absolute uri of a relative uri?如何获得相对uri的绝对uri?
【发布时间】:2011-07-30 21:53:24
【问题描述】:

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

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

如何从这个相对 uri 中获取绝对 uri?

谢谢,

【问题讨论】:

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


    【解决方案1】:
     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

    【讨论】:

    • HttpContext.Current.Request.ApplicationPath 只返回“/”,所以这种方法也不起作用。有什么想法吗?
    【解决方案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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 2022-01-17
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多