如何将相对URL转换为完整URL?

时间:2008-09-24 09:41:35

标签: asp.net

这可能更容易通过一个例子来解释。我正试图找到一种转换相对网址的方法,例如将“/Foo.aspx”或“〜/ Foo.aspx”写入完整的URL,例如http://localhost/Foo.aspx。这样,当我部署到测试或阶段时,网站运行的域名不同,我会得到http://test/Foo.aspxhttp://stage/Foo.aspx

有什么想法吗?

13 个答案:

答案 0 :(得分:58)

玩这个(修改后的from here

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

答案 1 :(得分:38)

这个被击败了,但我想我会发布自己的解决方案,我觉得这个解决方案比许多其他答案更清晰。

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();
}

答案 2 :(得分:34)

您只需使用page.request.url创建一个新URI,然后获取AbsoluteUri

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

答案 3 :(得分:5)

这是我执行此操作的辅助功能

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

答案 4 :(得分:4)

我以为我会使用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));
    }
}

答案 5 :(得分:2)

使用.NET Uri类来组合您的相对路径和主机名 http://msdn.microsoft.com/en-us/library/system.uri.aspx

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

答案 7 :(得分:1)

简单地:

url = new Uri(baseUri, url);

答案 8 :(得分:1)

在ASP.NET MVC中,您可以使用HtmlHelperUrlHelper的重载来获取protocolhost参数。当这些参数中的任何一个非空时,帮助程序生成绝对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);
}

从Razor视图中使用它,例如:

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

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

这可以作为off Page的扩展,就像ResolveUrl和ResolveClientUrl一样,用于webforms。如果您想要或需要在非webforms环境中使用它,请随意将其转换为HttpResponse扩展。它在标准和非标准端口上正确处理http和https,并且如果有用户名/密码组件。它也不使用任何硬编码字符串(即://)。

答案 10 :(得分: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.
//

答案 11 :(得分:0)

使用localhost和其他端口修改其他答案...我正在使用ex。电子邮件链接你可以从应用程序的任何部分调用,不仅仅是在页面或用户控件中,我把它放在Global中,不需要传递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)
                    );

            }

答案 12 :(得分:0)

在ASP.NET MVC中,您可以使用Url.Content(relativePath)转换为绝对网址

相关问题