How to URL encode a dictionary in C# with bracket notation

Viewed 42

Let's say I have the following class:

public class TestClass
    {
        public Dictionary<string, string> Property1 { get; set; }

    }

If I do the following:

var dictionary = new Dictionary<string, string>();
dictionary.add("key1", "value1");
dictionary.add("key2", "value2");

var newClass = new TestClass();
newClass.Property1 = dictionary;

I am trying to URL encode this dictionary to the following:

https://baseaddress.com/resource/?Property1[key1]=value1&Property1[key2]=value2

When attempting to URL encode the dictionary via HttpUtility it is returning the ToString() method of the Dictionary which comes out as:

System.Collections.Generic.Dictionary`2[System.String,System.String]

I am trying to pass this dictionary to a .netcore API that binds to a similar Dictionary<string, string>

Edit

I was able to get it working by using the following code:

            var builder = new UriBuilder(uri);
            var query = HttpUtility.ParseQueryString(string.Empty);

            foreach (var propInfo in obj.GetType().GetProperties())
            {
                var propName = propInfo.Name;
                var propValue = propInfo.GetValue(obj);

                if (propValue != null)
                {
                    var dict = propValue as IDictionary;
                    if (dict != null)
                    {
                        foreach (var key in dict.Keys)
                        {
                            var keyName = key;
                            var keyValue = dict[key];
                            query.Add($"{propName}[{keyName}]", keyValue.ToString());
                        }
                    }

                    else
                    {
                        query.Add(propName, propValue.ToString());
                    }
                }
            }

            builder.Query = query.ToString();
            return builder.Uri;

I was hoping there was a more efficient way to make this work.

1 Answers

If you want to get the standard format and avoid any problem with your QueryString you can "leverage" .net core approach which indeed is a way larger than the old approach. With that said here is what you can do: One thing....Notice that they are strings so you can add your brackets :)

Dictionary<String,StringValues>() queryString = QueryHelpers.ParseQuery("?param1=value");    
    
StringValues secondValue=StringValues.Concat(queryString["param2"], "my other value");
parsedQueryString["yourkey"] = secondValue;
//At this point you can start concatenating as many time as needed.
    
    
QueryString.Create(parsedQueryString).ToString();
// creates the following string "?param1=value&param2=my%20other%20value"

A plus :)

// Getting a param value
var param2Value = queryString["param2"];

param2Value.ToString(); // Get the values concatenated together
param2Value.ToArray(); // Gets an array of strings

// Modifying a parameter
queryString["param1"] = "another value";
// NOTE, if there were two values, this overwrites both and leaves a single value
Related