C#中来自基址+相对URL的绝对URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/128990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Absolute URL from base + relative URL in C#
提问by Romain Verdier
I have a base URL :
我有一个基本网址:
http://my.server.com/folder/directory/sample
And a relative one :
还有一个相对的:
../../other/path
How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the Uri
class or something similar.
如何从中获取绝对 URL?使用字符串操作非常简单,但我想以安全的方式,使用Uri
类或类似的东西来做到这一点。
It's for a standard a C# app, not an ASP.NET one.
它适用于标准的 C# 应用程序,而不是 ASP.NET 应用程序。
采纳答案by Mark Cidade
var baseUri = new Uri("http://my.server.com/folder/directory/sample");
var absoluteUri = new Uri(baseUri,"../../other/path");
OR
或者
Uri uri;
if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri);
回答by Matas Vaitkevicius
Some might be looking for Javascript solution that would allow conversion of urls 'on the fly' when debugging
有些人可能正在寻找允许在调试时“即时”转换 url 的 Javascript 解决方案
var absoluteUrl = function(href) {
var link = document.createElement("a");
link.href = href;
return link.href;
}
use like:
使用像:
absoluteUrl("http://google.com")
absoluteUrl("http://google.com")
http://google.com/
http://google.com/
or
或者
absoluteUrl("../../absolute")
absoluteUrl("../../absolute")
http://stackoverflow.com/absolute
http://stackoverflow.com/absolute