Absolute URL from base + relative URL in C#

懵懂的女人 提交于 2019-12-18 01:31:08

问题


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.

It's for a standard a C# app, not an ASP.NET one.


回答1:


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



回答2:


Some might be looking for Javascript solution that would allow conversion of urls 'on the fly' when debugging

var absoluteUrl = function(href) {
    var link = document.createElement("a");
    link.href = href;
    return link.href;
} 

use like:

absoluteUrl("http://google.com")

http://google.com/

or

absoluteUrl("../../absolute")

http://stackoverflow.com/absolute



来源:https://stackoverflow.com/questions/128990/absolute-url-from-base-relative-url-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!