POSTing String Values with HttpClient in .NET
In ASP.NET web APIs, you can often encounter scenarios where you need to send simple string values to your API methods as part of a POST request. HttpClient provides a convenient mechanism to perform such requests in C#.
To create a POST request that sends a string value, follow these steps:
Here's an example code that demonstrates how to perform such a POST request:
using System; using System.Collections.Generic; using System.Net.Http; class Program { static void Main(string[] args) { Task.Run(() => MainAsync()); Console.ReadLine(); } static async Task MainAsync() { var client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:6740"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", "login") }); var result = await client.PostAsync("/api/Membership/exists", content); string resultContent = await result.Content.ReadAsStringAsync(); Console.WriteLine(resultContent); } }
This code creates a POST request for the "/api/Membership/exists" action in a web API, sending the string value "login" as part of the payload.
The above is the detailed content of How to POST String Values with HttpClient in .NET?. For more information, please follow other related articles on the PHP Chinese website!