ProfK ProfK - 8 months ago 66
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


var content = new StringContent("grant_type=password&username=" + username + "&password=" + password.ToClearString(), Encoding.UTF8,

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 Source

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()
            .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();