Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post complex type formatted as form-url-encoded using ASP.Net HttpClient

I need to HTTP POST a complex type to a web service (which I don't controll). I believe the web service was built using an older version of ASP.NET MVC. It model binds payloads formatted as form-url-encoded.

If I fire the following at it, it works perfectly. As you can see, I've manually created a collection of key/value pairs.

    var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("Username", "some-username"),
        new KeyValuePair<string, string>("Password", "some-password"),
        new KeyValuePair<string, string>("Product", "some-product")
    };

    var content = new FormUrlEncodedContent(values);

    var response = new HttpClient().PostAsync(url, content).Result;

But I don't want to have to do this, I just want to send complex types if I can.

var content = new ComplexType("some-username", "some-password", "some-product");

var response = new HttpClient().PostAsync(url, content).Result;

I believe there used to be a HttpRequestMessage<T> but that's been dropped in favour of

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json” HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

But I don't want to send Json or XML I want to send form-url-ecncoded without the hassle of converting complex types to collections of key/value pairs.

Essentially I'd also like to know the answer to this question that Jaans poses (His is the second comment to the second answer).

Can anyone advise please.

like image 350
Simon Lomax Avatar asked Jun 20 '13 15:06

Simon Lomax


1 Answers

Flurl [disclosure: I'm the author] provides a method that seems to be exactly what you're looking for:

using Flurl.Http;

var resp = await url.PostUrlEncodedAsync(new {
    Username = "some-username",
    Password = "some-password",
    Product = "some-product",
});

Flurl is small and portable, and uses HttpClient under the hood. It is available via NuGet:

PM> Install-Package Flurl.Http
like image 193
Todd Menier Avatar answered Nov 20 '22 14:11

Todd Menier