0

Given a url like https://somedomain.com:1234/someotherstuff?a=b#def the browser's URL class's origin property returns https://somedomain.com:1234

var url = new URL("https://somedomain.com:1234/someotherstuff?a=b#def");
console.log(url.origin);

prints

"https://somedomain.com:1234"

Is there an equivalent in .NET?

I see the Uri class but it doesn't seem to have a field that corresponds to origin above

Uri u = new Uri("https://somedomain.com:1234/someotherstuff?a=b#def");
Console.WriteLine(u.AbsolutePath);  //  /someotherstuff
Console.WriteLine(u.AbsoluteUri);   //  https://somedomain.com:1234/someotherstuff?a=b#def
Console.WriteLine(u.Fragment);      //  #def
Console.WriteLine(u.Host);          //  somedomain.com
Console.WriteLine(u.LocalPath);     //  /someotherstuff
Console.WriteLine(u.Port);          //  1234
Console.WriteLine(u.Query);         //  ?a=b
Console.WriteLine(u.DnsSafeHost);   //  somedomain.com
Console.WriteLine(u.HostNameType);  //  Dns
Console.WriteLine(u.Scheme);        //  https

From that it appears I need to do this

string origin = u.Scheme + 
                "://" + 
                u.host + 
                (String.IsNullOrEmpty(u.Port) ? "" : (":" + u.Port)

And possibly some other stuff I'm not aware of.

Is there already some cross platform (not Windows only) .NET function that will give me the equivalent of URL.origin?

gman
  • 100,619
  • 31
  • 269
  • 393
  • 2
    I found the answer right after I posted and voted to close. It's sad to me that SO, when suggesting possible answers while writing the question doesn't show the same suggestions as after the question is posted. The answer is `Uri.GetLeftPart()` – gman Jan 28 '16 at 10:47

1 Answers1

0

You could replace the PathAndQuery and the Fragements:

var url = new Uri("https://somedomain.com:1234/someotherstuff?a=b#def#a");
var newUrl = url.AbsoluteUri.Replace(url.PathAndQuery, String.Empty).Replace(url.Fragment, String.Empty);

Or you could cut the part after the Authority:

var url = new Uri("https://somedomain.com:1234/someotherstuff?a=b#def#a");
var authorityIndex = url.AbsoluteUri.IndexOf(url.Authority);
var newUrl = url.AbsoluteUri.Substring(0, authorityIndex + url.Authority.Length);
P. Wenger
  • 543
  • 3
  • 5