Michel Ayres
Michel Ayres

Reputation: 5985

How should I get a specific part of the URI

If I have the URI "http://www.test.com/something" and I want the "www.test.com" part. What should I use? (what is the best for this)

I asked this question in the CHAT, but didn't get so much luck.

Upvotes: 3

Views: 178

Answers (2)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

As comment stated, it may be important for which purpose you intend to use hostname.

Generally, I would use Uri.Authority, or combine components I need.

Authority provides two key components to locate a service: 1) hostname 2) port. Other two properties only give you hostname.

For example, if I was accessing website which is not hosted on default port, but for example 81 (http://example.com:81), I'd like to be informed about port number too.

Upvotes: 4

sloth
sloth

Reputation: 101072

Stick with Request.Url.Authority, so if your host has another port than 80, it will be displayed (if this important for you).


Example:

Uri baseUri = new Uri("http://www.test.com:8888/something");
Console.WriteLine(myUri.Authority);
Console.WriteLine(myUri.Host);  

Output:

www.test.com:8888
www.test.com


If you just want to display the host part to the user, no need to bother with DnsSafeHost anyway. You would use it if you need to convert a IPv6 address e.g. http://[fe80::200:39ff:fe36:1a2d%4]/temp/example.htm to fe80::200:39ff:fe36:1a2d%4 for name resolution.

Upvotes: 5

Related Questions