212

How can I create using C# and HttpClient the following POST request: User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6

I need such a request for my WEB API service:

[ActionName("exist")]
[HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{           
    return _membershipProvider.CheckIfExist(login);
}
Ievgen Martynov
  • 7,870
  • 8
  • 36
  • 52

5 Answers5

492
using System;
using System.Collections.Generic;
using System.Net.Http;

class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => MainAsync());
        Console.ReadLine();
    }

    static async Task MainAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("", "login")
            });
            var result = await client.PostAsync("/api/Membership/exists", content);
            string resultContent = await result.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
        }
    }
}
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    hm, my HttpClientExtensions does not have such overload... i use framework 4.0 – Ievgen Martynov Mar 02 '13 at 16:42
  • 1
    Which overload you do not have? Make sure you have installed the [`Microsoft.AspNet.WebApi.Client`](http://nuget.org/packages/Microsoft.AspNet.WebApi.Client/) NuGet to your project. The `HttpClient` class is built in .NET 4.5, not in .NET 4.0. If you want to use it in .NET 4.0 you need the NuGet! – Darin Dimitrov Mar 02 '13 at 16:42
  • 1
    First C# SSSCE I come across. As if it were such a breeze to get it running if you're coming from a language with a proper IDE. – Buffalo Apr 01 '15 at 06:12
  • 21
    Just a note that using HttpClient in using statement is a [mistake](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) – ren Mar 16 '17 at 19:06
  • 31
    You should private static readonly HttpClient _client = new HttpClient(); instead https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ – Sameer Alibhai May 09 '17 at 15:05
  • Result is ***UrlEncoded Content***, not ***JSON format*** for request? – Kiquenet Feb 23 '18 at 08:40
  • 1
    @Sameer nice point.. I recommend everyone to check that post, Its some serious performance improvement. – Rajshekar Reddy Mar 01 '18 at 08:17
  • what if I wanted to use `new KeyValuePair("", "login" + someOtherString)` – greg Mar 19 '18 at 20:07
41

Below is example to call synchronously but you can easily change to async by using await-sync:

var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("login", "abc")
            };

var content = new FormUrlEncodedContent(pairs);

var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};

    // call sync
var response = client.PostAsync("/api/membership/exist", content).Result; 
if (response.IsSuccessStatusCode)
{
}
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • 1
    I don't think this will work. you should replace "login" with empty string, it should be KeyValuePair("", "abc"), see the accepted answer. – joedotnot Feb 28 '19 at 01:54
  • this works for me, work on php webservice that is calling $company_id = $_POST("company_id"); like that. If I send as json, php cannot work. – TPG Mar 19 '20 at 08:38
29

Here I found this article which is send post request using JsonConvert.SerializeObject() & StringContent() to HttpClient.PostAsync data

static async Task Main(string[] args)
{
    var person = new Person();
    person.Name = "John Doe";
    person.Occupation = "gardener";

    var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
    var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

    var url = "https://httpbin.org/post";
    using var client = new HttpClient();

    var response = await client.PostAsync(url, data);

    string result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}
SilverM-A
  • 123
  • 1
  • 7
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
9

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}
oneNiceFriend
  • 6,691
  • 7
  • 29
  • 39
2

You could do something like this

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist");

req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";         
req.ContentLength = 6;

StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();

And then strReponse should contain the values returned by your webservice

Axel
  • 361
  • 2
  • 6