articles » current » asp-net-core » post-to-endpoint

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("", 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();

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.