ProfK ProfK - 15 days ago 8
HTTP Question

Is there a utility to serialise an object as HTTP content type "application/x-www-form-urlencoded"?

I've never had to do this before, because it's always only been an actual form that I've posted as that content type, but recently I had to post three variables like that, and I resorted to a sordid concatenation with

&
and
=
:

var content = new StringContent("grant_type=password&username=" + username + "&password=" + password.ToClearString(), Encoding.UTF8,
"application/x-www-form-urlencoded");


I'm sure there must be a utility method that would do that, and do it better, with any necessary encoding. What would that be?

Answer

Use reflection to get the property names and values and then use them to create a System.Net.Http.FormUrlEncodedContent

public static class FormUrlEncodedContentExtension {

    public static FormUrlEncodedContent ToFormUrlEncodedContent(this object obj) {
        var nameValueCollection = obj.GetType()
            .GetProperties()
            .ToDictionary(p => p.Name, p => (p.GetValue(obj) ?? "").ToString());

        var content = new FormUrlEncodedContent(nameValueCollection);

        return content;
    }

}

From there it is a simple matter of calling the extension method on an object to convert it to a FormUrlEncodedContent

var model = new MyModel {
    grant_type = "...",
    username = "...",
    password = "..."
};

var content = model.ToFormUrlEncodedContent();