2008-09-24 131 views
59

這可能更容易解釋一個例子。我試圖找到轉換相對網址的方法,例如「/Foo.aspx」或「〜/ Foo.aspx」轉換成完整的URL,例如http://localhost/Foo.aspx。這種方式,當我部署測試或階段,其中網站運行的域名是不同的,我會得到http://test/Foo.aspxhttp://stage/Foo.aspx如何將相對URL轉換爲完整的URL?

任何想法?

+0

2相關答案:HTTP://計算器.com/questions/7413466/how-can-i-get-the-baseurl-of-site和http://stackoverflow.com/questions/3933662/in-asp-net-what-is-the-quickest-way -to-get-the-base-url-for-a-request – 2013-07-10 19:41:16

回答

57

有這個戲(改性from here

public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) { 
    return string.Format("http{0}://{1}{2}", 
     (Request.IsSecureConnection) ? "s" : "", 
     Request.Url.Host, 
     Page.ResolveUrl(relativeUrl) 
    ); 
} 
+3

我當時希望有一些內置於ASP .NET的東西,所以我不必進入查看協議,端口等的所有業務但是這應該完成這項工作。 – gilles27 2008-09-24 09:49:58

+7

只是一個註釋:當我使用它時,我在主機和頁面url之間添加了Request.URL.Port,所以它可以在Visual Web Dev測試服務器上工作。 – ine 2008-10-15 19:57:06

+0

@roviuser Tthis與MVC無關。這只是一個實用功能,所以你可以隨心所欲地粘貼它。 – Oli 2012-08-31 14:03:52

5

這是我的輔助函數來做到這一點

public string GetFullUrl(string relativeUrl) { 
    string root = Request.Url.GetLeftPart(UriPartial.Authority); 
    return root + Page.ResolveUrl("~/" + relativeUrl) ; 
} 
2

這是我創建做轉換輔助功能。

//"~/SomeFolder/SomePage.aspx" 
public static string GetFullURL(string relativePath) 
{ 
    string sRelative=Page.ResolveUrl(relativePath); 
    string sAbsolute=Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,sRelative); 
    return sAbsolute; 
} 
30

你只需要使用page.request.url創建一個新的URI,然後得到了AbsoluteUri

New System.Uri(Page.Request.Url, "Foo.aspx").AbsoluteUri 
37

這一個被打致死,但我想我會發布我自己的解決方案,我認爲比許多其他答案更清潔。

public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues) 
{ 
    return url.Action(actionName, controllerName, routeValues, url.RequestContext.HttpContext.Request.Url.Scheme); 
} 

public static string AbsoluteContent(this UrlHelper url, string path) 
{ 
    Uri uri = new Uri(path, UriKind.RelativeOrAbsolute); 

    //If the URI is not already absolute, rebuild it based on the current request. 
    if (!uri.IsAbsoluteUri) 
    { 
     Uri requestUrl = url.RequestContext.HttpContext.Request.Url; 
     UriBuilder builder = new UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port); 

     builder.Path = VirtualPathUtility.ToAbsolute(path); 
     uri = builder.Uri; 
    } 

    return uri.ToString(); 
} 
1

簡單:

url = new Uri(baseUri, url); 
3

我想我會分享我的方法使用Uri類和一些神奇的延長在ASP.NET MVC這樣做。

public static class UrlHelperExtensions 
{ 
    public static string AbsolutePath(this UrlHelper urlHelper, 
             string relativePath) 
    { 
     return new Uri(urlHelper.RequestContext.HttpContext.Request.Url, 
         relativePath).ToString(); 
    } 
} 

然後,您可以輸出使用絕對路徑:

// gives absolute path, e.g. https://example.com/customers 
Url.AbsolutePath(Url.Action("Index", "Customers")); 

它看起來有點醜陋具有嵌套的方法調用,所以我更喜歡用共同的行動方法進一步擴大UrlHelper,這樣我可以這樣做:

// gives absolute path, e.g. https://example.com/customers 
Url.AbsoluteAction("Index", "Customers"); 

Url.AbsoluteAction("Details", "Customers", new{id = 123}); 

完整的擴展類如下:

public static class UrlHelperExtensions 
{ 
    public static string AbsolutePath(this UrlHelper urlHelper, 
             string relativePath) 
    { 
     return new Uri(urlHelper.RequestContext.HttpContext.Request.Url, 
         relativePath).ToString(); 
    } 

    public static string AbsoluteAction(this UrlHelper urlHelper, 
             string actionName, 
             string controllerName) 
    { 
     return AbsolutePath(urlHelper, 
          urlHelper.Action(actionName, controllerName)); 
    } 

    public static string AbsoluteAction(this UrlHelper urlHelper, 
             string actionName, 
             string controllerName, 
             object routeValues) 
    { 
     return AbsolutePath(urlHelper, 
          urlHelper.Action(actionName, 
              controllerName, routeValues)); 
    } 
} 
1

在ASP.NET MVC中,你可以使用HtmlHelperUrlHelper的重載採取或host參數。當這些參數中的任何一個都不爲空時,助手會生成一個絕對URL。這是一個擴展方法我使用:

public static MvcHtmlString ActionLinkAbsolute<TViewModel>(
    this HtmlHelper<TViewModel> html, 
    string linkText, 
    string actionName, 
    string controllerName, 
    object routeValues = null, 
    object htmlAttributes = null) 
{ 
    var request = html.ViewContext.HttpContext.Request; 
    var url = new UriBuilder(request.Url); 
    return html.ActionLink(linkText, actionName, controllerName, url.Scheme, url.Host, null, routeValues, htmlAttributes); 
} 

而從剃刀視圖,例如用它:

@Html.ActionLinkAbsolute("Click here", "Action", "Controller", new { id = Model.Id }) 
0

古老的問題,但我想我會回答它,因爲許多答案是不完整的。

public static string ResolveFullUrl(this System.Web.UI.Page page, string relativeUrl) 
{ 
    if (string.IsNullOrEmpty(relativeUrl)) 
     return relativeUrl; 

    if (relativeUrl.StartsWith("/")) 
     relativeUrl = relativeUrl.Insert(0, "~"); 
    if (!relativeUrl.StartsWith("~/")) 
     relativeUrl = relativeUrl.Insert(0, "~/"); 

    return $"{page.Request.Url.Scheme}{Uri.SchemeDelimiter}{page.Request.Url.Authority}{VirtualPathUtility.ToAbsolute(relativeUrl)}"; 
} 

這可以作爲關閉Page的擴展,就像ResolveUrl和ResolveClientUrl for webforms一樣。如果您想要或需要在非webforms環境中使用它,請隨意將其轉換爲HttpResponse擴展。它可以在標準和非標準端口上正確處理http和https,以及是否有用戶名/密碼組件。它也不使用任何硬編碼的字符串(即://)。

0

這是一種方法。這不關心字符串是相對的還是絕對的,但是你必須提供一個baseUri來使用它。

/// <summary> 
    /// This function turns arbitrary strings containing a 
    /// URI into an appropriate absolute URI. 
    /// </summary> 
    /// <param name="input">A relative or absolute URI (as a string)</param> 
    /// <param name="baseUri">The base URI to use if the input parameter is relative.</param> 
    /// <returns>An absolute URI</returns> 
    public static Uri MakeFullUri(string input, Uri baseUri) 
    { 
     var tmp = new Uri(input, UriKind.RelativeOrAbsolute); 
     //if it's absolute, return that 
     if (tmp.IsAbsoluteUri) 
     { 
      return tmp; 
     } 
     // build relative on top of the base one instead 
     return new Uri(baseUri, tmp); 
    } 

在ASP.NET情況下,你可以這樣做:使用前從對方的回答與本地主機和其他端口修改

Uri baseUri = new Uri("http://yahoo.com/folder"); 
Uri newUri = MakeFullUri("/some/path?abcd=123", baseUri); 
// 
//newUri will contain http://yahoo.com/some/path?abcd=123 
// 
Uri newUri2 = MakeFullUri("some/path?abcd=123", baseUri); 
// 
//newUri2 will contain http://yahoo.com/folder/some/path?abcd=123 
// 
Uri newUri3 = MakeFullUri("http://google.com", baseUri); 
// 
//newUri3 will contain http://google.com, and baseUri is not used at all. 
// 
0

... IM。郵件鏈接。您可以從應用程序的任何部分調用,不僅在頁面或用戶控件,我把這個全球對於不需要在傳遞HttpContext.Current.Request作爲參數

  /// <summary> 
      /// Return full URL from virtual relative path like ~/dir/subir/file.html 
      /// usefull in ex. external links 
      /// </summary> 
      /// <param name="rootVirtualPath"></param> 
      /// <returns></returns> 
      public static string GetAbsoluteFullURLFromRootVirtualPath(string rootVirtualPath) 
      { 

       return string.Format("http{0}://{1}{2}{3}", 
        (HttpContext.Current.Request.IsSecureConnection) ? "s" : "" 
        , HttpContext.Current.Request.Url.Host 
        , (HttpContext.Current.Request.Url.IsDefaultPort) ? "" : ":" + HttpContext.Current.Request.Url.Port 
        , VirtualPathUtility.ToAbsolute(rootVirtualPath) 
        ); 

      }