.NET HttpClient. How to POST string value?
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);
}
}
}
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)
{
}
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);
}