2008-09-24 40 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) 
        ); 

      } 
相关问题