我有一个基本网址:
http://my.server.com/folder/directory/sample
还有一个相对的:
../../other/path
如何从中获取绝对 URL?使用字符串操作非常简单,但我想以安全的方式使用Uri
类或类似的东西来做到这一点。
它适用于标准的 C# 应用程序,而不是 ASP.NET 应用程序。
var baseUri = new Uri("http://my.server.com/folder/directory/sample");
var absoluteUri = new Uri(baseUri,"../../other/path");
或者
Uri uri;
if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri);
有些人可能正在寻找允许在调试时“即时”转换 url 的 Javascript 解决方案
var absoluteUrl = function(href) {
var link = document.createElement("a");
link.href = href;
return link.href;
}
像这样使用:
absoluteUrl("http://google.com")
http://google.com/
或者
absoluteUrl("../../absolute")
http://stackoverflow.com/absolute