Time to share something neath, and that is the possibility of using bitwise combinations of System.UriComponents
(MSDN-docs) with System.Uri.GetComponents
(MSDN-docs) to easily reformat an URL.
Lets have a look at some code that dumps out the individual values of an URL and finally makes use of GetComponents
to “pick some parts of interest”.
var uri = new Uri(
"https://superman:[email protected]:8081/todo/list/?foo=bar");
var values = Enum.GetValues(typeof (UriComponents)).OfType();
foreach (var value in values)
{
Console.WriteLine("{0} = {1}",
value,
uri.GetComponents(value, UriFormat.UriEscaped));
}
The output of the code above:
Scheme = https
UserInfo = superman:steel
Host = my-sub.my-domain.com
Port = 8081
SchemeAndServer = https://my-sub.my-domain.com:8081
Path = todo/list/
Query = foo=bar
PathAndQuery = /todo/list/?foo=bar
HttpRequestUrl = https://my-sub.my-domain.com:8081/todo/list/?foo=bar
Fragment =
AbsoluteUri = https://superman:[email protected]:8081/todo/list/?foo=bar
StrongPort = 8081
HostAndPort = my-sub.my-domain.com:8081
StrongAuthority = superman:[email protected]:8081
NormalizedHost = my-sub.my-domain.com
KeepDelimiter =
SerializationInfoString = https://superman:[email protected]:8081/todo/list/?foo=bar
Now lets look at how we can make use of bitwise combinations, to remove: UserInfo, Port and Path
Console.WriteLine(uri.GetComponents(
UriComponents.AbsoluteUri &
~UriComponents.UserInfo &
~UriComponents.Port &
~UriComponents.Path, UriFormat.UriEscaped));
Which outputs:
https://my-sub.my-domain.com?foo=bar
As you can see, it removed: UserInfo, Port and Path
so that only Scheme, Host and Query
were left.
That’s all. A neat little solution to have in your toolbox.
//Daniel