In this short post, I’m going to show how to get query value URL by key. Let’s say we have a sample URL like this.
https://www.justsimplycode.com/fake/url?queryA=123&queryB=ABC
There is this method ParseQueryString from HttpUtility, which can be imported from System.Web, that parses URL to a name value collection.
var url = "https://www.justsimplycode.com/fake/url?queryA=123&queryB=ABC";
var uri = new Uri(url);
var queriesCollection = HttpUtility.ParseQueryString(uri.Query);
foreach (var key in queriesCollection.AllKeys)
{
Console.WriteLine($"{key}: {queriesCollection.Get(key)}");
}
This is the result

One thing to watch out for is that you can pass a string to ParseQueryString instead of Uri. However, passing a string results in incorrect key for the for the first query.
var url = "https://www.justsimplycode.com/fake/url?queryA=123&queryB=ABC";
var queriesCollection = HttpUtility.ParseQueryString(url);
foreach (var key in queriesCollection.AllKeys)
{
Console.WriteLine($"{key}: {queriesCollection.Get(key)}");
}
The above code will result in this

This is probably not what we want.