Sending String Data via .NET HttpClient POST Request
This guide demonstrates how to construct a POST request in C# using HttpClient
to send string data, replicating the following request parameters:
The target is a WEB API endpoint with this method:
<code class="language-csharp">[ActionName("exist")] [HttpPost] public bool CheckIfUserExist([FromBody] string login) { return _membershipProvider.CheckIfExist(login); }</code>
Implementation
The following C# code utilizes HttpClient
to achieve this POST request:
<code class="language-csharp">using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { await MainAsync(); Console.ReadKey(); // Keep console window open until a key is pressed } static async Task MainAsync() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:6740"); var content = new StringContent("login", System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await client.PostAsync("/api/Membership/exists", content); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } } }</code>
For ASP.NET 4.0 projects, remember to install the Microsoft.AspNet.WebApi.Client
NuGet package before running this code. This ensures proper functionality with the HttpClient
class.
The above is the detailed content of How to POST String Values with .NET HttpClient?. For more information, please follow other related articles on the PHP Chinese website!