;

How to Get Specific QueryString Parameter Value from a String Value in C#


Tutorialsrack 26/01/2022 C# ASP.NET MVC ASP.NET WEB API ASP.NET ASP.NET Core

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.

Example 1: Using HttpUtility.ParseQueryString Method

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&param2=bad&param3=29Cjs7/0+5iCCx4NaG4E67aFCXiqG6nAqaDOIopMKn3SbFA5p30Iw==&param4=helloWorld");
var qs = System.Web.HttpUtility.ParseQueryString(myUri.Query);

//Get the Value of "param1"
var ParamValue = qs.Get("param1");
//Output => "good"

Example 2: Using Extension Method

You can also use the extension method as given below to get the param value of specific query string parameters.

Code - Uri Extention Method
        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&param2=bad&param3=29Cjs7/0+5iCCx4NaG4E67aFCXiqG6nAqaDOIopMKn3SbFA5p30Iw==&param4=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!


Related Posts



Comments

Recent Posts
Tags