Send Http Post Request In. Net

Send Http Post Request In. Net

How can I make an HTTP POST request and send data in the body ?

15 Answers

There are several ways to perform HTTP GET and POST requests:


Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+ .

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

See HttpClientFactory for a dependency injection solution.


  • POST

      var values = new Dictionary<string, string>
      {
          { "thing1", "hello" },
          { "thing2", "world" }
      };
    
      var content = new FormUrlEncodedContent(values);
    
      var response = await client.PostAsync("", content);
    
      var responseString = await response.Content.ReadAsStringAsync();
    
  • GET

      var responseString = await client.GetStringAsync("");
    

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.