Convert dynamic to query string

3

Is there a more "elegant" way of converting a dynamic to a query string ?

I'm currently doing with several Replace() but it's not quite what I wanted.

string data = new
{
    email = email,
    password = password
}
.ToString()
.Replace(',', '&')
.Replace(' ', char.MinValue)
.Replace('{', char.MinValue)
.Replace('}', char.MinValue);

I tried to create an extension that would solve this case for me, but it does not work with type dynamic

public static StringContent ToQueryString(this object model)
{
    Dictionary<string, string> query = new Dictionary<string, string>();

    dynamic data = model as dynamic;

    foreach (PropertyInfo property in data.GetType().GetProperties())
        query.Add(property.Name, property.GetValue(data, null));

    return new StringContent(string.Join("&", query));
}
    
asked by anonymous 05.11.2017 / 13:52

1 answer

3

First, you should use what you have ready to encode the URL ( .NET Framework and .NET Core ).

You should not create an extension method in object , it will be available for everything and I think you have no idea how much this is going to bring you problems.

Alias, when using object you're probably doing something wrong. It is useful in very specific cases that rare problems need and even so probably due to platform limitation.

If dynamic is not working take it, after all it has no use there. It almost always does not.

That is, this code is full of unnecessary resource abuse.

Of course there are other ways to reach the goal better, and I'm not saying it's just more elegant, it's being more robust, more correct.

using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() => WriteLine(ToQueryString(new { nome = "Nome", valor = 10 }));

    public static string ToQueryString<T>(T model) {
        var query = new Dictionary<string, string>();
        foreach (var property in typeof(T).GetProperties())
            query.Add(property.Name, property.GetValue(model, null).ToString());
        return string.Join("&", query);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .

    
05.11.2017 / 15:50