Convert Dynamic to query string

Asked

Viewed 148 times

3

Is there any more "elegant" way to convert a dynamic for 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 doesn’t work with the guy 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));
}
  • I didn’t quite understand your code, but apparently if you want to take an object of any kind and turn into query String would be this ?

1 answer

3


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

You should not create an extension method on object, will be available for everything and I think you have no idea how much this will bring you trouble.

By the way, when you use object He’s probably doing something wrong. It is useful in very specific cases that rare problems need and even so probably by platform limitation.

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

That is, this code is full of abuses of unnecessary resources.

Surely there are other ways to achieve the goal better, and I’m not talking about just being more elegant, is to be 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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.