用一个例子可以更容易地解释这一点.我正试图找到一种方法将相对URL,例如"/Foo.aspx"或"〜/ Foo.aspx"转换为完整的URL,例如http://localhost/Foo.aspx.这样,当我部署到测试或阶段时,网站运行的域名不同,我将获得http://test/Foo.aspx和http://stage/Foo.aspx.
有任何想法吗?
玩这个(从这里修改)
public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) { return string.Format("http{0}://{1}{2}", (Request.IsSecureConnection) ? "s" : "", Request.Url.Host, Page.ResolveUrl(relativeUrl) ); }
这个被击败了,但我想我会发布自己的解决方案,我认为它比许多其他答案更清晰.
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(); }
你只需要使用它创建一个新的URI page.request.url
然后得到AbsoluteUri
它:
New System.Uri(Page.Request.Url, "Foo.aspx").AbsoluteUri
这是我的帮手功能
public string GetFullUrl(string relativeUrl) { string root = Request.Url.GetLeftPart(UriPartial.Authority); return root + Page.ResolveUrl("~/" + relativeUrl) ; }