In this article, you’ll learn how to get the specific query string parameter value from a string value in c#. We recently needed to parse and modify some query strings while building new redirects. There are various ways to achieve this but in this post, we are using the HttpUtility.ParseQueryString method and extension method to get the specific query string parameter value from the string URL.
You can use the static ParseQueryString()
method of System.Web.HttpUtility
class that returns HttpQSCollection
.
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad¶m3=29Cjs7/0+5iCCx4NaG4E67aFCXiqG6nAqaDOIopMKn3SbFA5p30Iw==¶m4=helloWorld");
var qs = System.Web.HttpUtility.ParseQueryString(myUri.Query);
//Get the Value of "param1"
var ParamValue = qs.Get("param1");
//Output => "good"
You can also use the extension method as given below to get the param value of specific query string parameters.
public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (uri.Query.Length == 0)
return new Dictionary<string, string>();
return uri.Query.TrimStart('?')
.Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(parameter => parameter.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(parts => parts[0],
parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
.ToDictionary(grouping => grouping.Key,
grouping => string.Join(",", grouping));
}
You can call this extension Method like this:
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad¶m3=29Cjs7/0+5iCCx4NaG4E67aFCXiqG6nAqaDOIopMKn3SbFA5p30Iw==¶m4=helloWorld");
//Get the Value of "param3"
var ParamValue = myUri.DecodeQueryParameters().Where(item => item.Key == "param3").FirstOrDefault().Value;
//Output => "29Cjs7/0+5iCCx4NaG4E67aFCXiqG6nAqaDOIopMKn3SbFA5p30Iw=="
I hope this article will help you to understand how to get the specific query string parameter value from a string value in c#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments