28

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.

Llyle
  • 5,980
  • 6
  • 39
  • 56
Romain Verdier
  • 12,833
  • 7
  • 57
  • 77

2 Answers2

50
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);
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • May I ask, is there any JavaScript equivalent of the code above? – Nordin May 20 '09 at 00:48
  • 1
    One point noting, that for some unknown reason `new Uri` **decodes** html entities, and if this makes a difference, this will lead to incorrect URL. For example I have a page, lets say `hello%2Fworld.html` page. After making it absolute I get `hello/world.html` which is of course incorrect. – greenoldman Apr 02 '13 at 21:23
  • 42 votes but it doesn't work. First snipped yields: http://my.server.com/other/path which is missing the /folder/ part. – Martin Capodici Oct 18 '14 at 23:26
  • @MartinCapodici The OP specified a different base URI than for what you are specifying. In your case, you can can use `"http://my.server.com/folder/directory/sample/"` as the base URI. – Mark Cidade Oct 20 '14 at 18:02
0

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

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265