PROWAREtech
ASP.NET Core: How to Issue a POST Request to an Endpoint using C#
Using C#, POST JSON to a REST API endpoint; how to receive JSON data from a REST API.
This article requires ASP.NET Core, and is compatible with .NET Core 3.1, .NET 6 and .NET 8.
To GET data from an endpoint, see this article.
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.
POST JSON to Endpoint
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();
POST with JSON Web Token Bearer Authentication
It is simple to POST to an endpoint using JWT Bearer Authentication. Simply use the HttpRequestMessage
class and the SendAsync()
method.
private async Task PostJsonWithJwtAuth()
{
object? responseObject = null; // NOTE: replace "object" with the class name
string json = System.Text.Json.JsonSerializer.Serialize(new { data = "ABCD1234" });
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
var requestMsg = new HttpRequestMessage(HttpMethod.Post, "http://0.0.0.0/endpoint");
requestMsg.Content = new StringContent(json, Encoding.UTF8, "application/json");
string jwt = "asidlfbvc87w4tguiwebo87w4gqowuy4bfoq4837yo8f3fl"; // NOTE: THIS IS THE JSON WEB TOKEN; REPLACE WITH A REAL JWT
requestMsg.Headers.Add("Authorization", "Bearer " + jwt);
var response = await client.SendAsync(requestMsg);
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// NOTE: THEN TOKEN HAS EXPIRED; HANDLE THIS SITUATION
}
else if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
responseObject = null;
else if (response.IsSuccessStatusCode)
responseObject = await response.Content.ReadFromJsonAsync<object>(); // NOTE: replace "object" with the class name
}
}
await PostJsonWithJwtAuth();
Comment