PROWAREtech








ASP.NET Core: How to POST to an Endpoint using C#
Using C#, post JSON to a REST API endpoint.
This article requires ASP.NET Core.
It is very easy to post JSON data to an endpoint using HttpClient
. WebClient
and HttpWebRequest
should not be used as they are deprecated as of the writing of this article.
private async Task PostJson()
{
string json = System.Text.Json.JsonSerializer.Serialize(new { name = "test" });
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
var response = await client.PostAsync("http://0.0.0.0/endpoint", new StringContent(json, Encoding.UTF8, "application/json"));
var repsonseObject = System.Text.Json.JsonSerializer.Deserialize<object> // NOTE: replace "object" with class name
(await response.Content.ReadAsStringAsync());
// NOTE: use responseObject here
}
}
await PostJson();
Comment