221

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);
}
4
  • 1
    What HTTP client are you using in the image? Commented Feb 10, 2016 at 18:37
  • telerik.com/fiddler Commented Feb 11, 2016 at 17:40
  • 1
    The service is Web Api MVC. JSON format for request? Commented Feb 23, 2018 at 8:45
  • Related post - POSTing JsonObject With HttpClient From Web API Commented Sep 7, 2021 at 4:21

5 Answers 5

500

In ASP.NET 4.5 (for 4.0, you need to install the Microsoft.AspNet.WebApi.Client NuGet package):

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()
    {
        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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Result is UrlEncoded Content, not JSON format for request?
what if I wanted to use new KeyValuePair<string, string>("", "login" + someOtherString)
43

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)
{
}

2 Comments

I don't think this will work. you should replace "login" with empty string, it should be KeyValuePair<string, string>("", "abc"), see the accepted answer.
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.
34

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);
}

1 Comment

OP is trying to send a single string, not a serialized JSON object. API accepts string, it will not accept Person.
10

Here is a small part from the POST section of How to call an api with asp.net:

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;
}

3 Comments

The request is form-urlencoded so I don't think JSON will work
It's form-urlencoded. Anyways, JSON format for DateTime properties? serialization issues?
I don't seem to notice your method "PostAsJsonAsync" It is not available in my HttpClient instance.
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

2 Comments

The question here was about how to use the new HttpClient and not the old WebRequest.
True I didn't noticed, i'll leave the post anyway in case someone needs the old one...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.