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

I need an HTTP POST complex type for a web service (which I don't control). I believe that the web service was created using the old version of ASP.NET MVC. This model binds a payload formatted as form-url-encoded .

If I run the following on it, it works fine. As you can see, I 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 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 an HttpRequestMessage<T> , but that was dropped in favor

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 problems with converting complex types to collections of key / value pairs.

In fact, I would also like to know the answer to this question that Jaans creates (his second comment on the second answer).

Someone can advise.

+6
source share
3 answers

Flurl [disclosure: I am the author] provides a method that seems to be exactly what you are 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 the HttpClient under the hood. It is available through NuGet:

 PM> Install-Package Flurl.Http 
+1
source

Since you almost have a solution that really works, I would say just go with it. Organize your code inside the extension method so you can publish it, for example:

 public static async Task<HttpResponseMessage> PostAsFormUrlEncodedAsync<T>( this HttpClient httpClient, T value) { // Implementation } 

Your implementation simply requires to serialize your object in form-encoded values, which you should easily do with reflection.

You can then invoke the code in the same way as for JSON or XML.

0
source

You can do it:

 var content = new ComplexType("some-username", "some-password", "some-product"); var response = new HttpClient().PostAsync<ComplexType>(url, content, new FormUrlEncodedMediaTypeFormatter()).Result; 
-1
source

Source: https://habr.com/ru/post/947750/


All Articles