Overview
This method allows you to send data in the application/x-www-form-urlencoded format, which is the same format used by standard HTML <form> tags. By using the FormUrlEncodedContent class, key-value pairs are automatically URL-encoded, and the appropriate Content-Type header is added to the POST request.
Specifications (Input/Output)
- Input: Data to be sent (a collection of key-value pairs).
- Output: Server response (response body).
- Prerequisite: Uses the standard .NET library (
System.Net.Http).
Basic Usage
Pack your data into a Dictionary<string, string> and pass it to the constructor of FormUrlEncodedContent.
var formData = new Dictionary<string, string>
{
["username"] = "user01",
["message"] = "Hello C#"
};
// Automatic encoding (e.g., spaces become +) is performed
using var content = new FormUrlEncodedContent(formData);
// Execute POST
var response = await client.PostAsync("https://example.com/api/login", content);
Full Code Example
The following console application demonstrates sending “search settings” in form format and receiving the result.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
// Reuse HttpClient to avoid socket exhaustion
private static readonly HttpClient _httpClient = new HttpClient();
static async Task Main()
{
// Target URL for testing
string url = "https://httpbin.org/post";
Console.WriteLine($"Destination: {url}");
try
{
// 1. Prepare data to be sent
// Define keys and values in a dictionary
var parameters = new Dictionary<string, string>
{
["keyword"] = "network",
["encode"] = "UTF-8",
["maxsize"] = "20",
["comment"] = "C# & .NET" // Symbols and spaces are automatically encoded
};
// 2. Create content (application/x-www-form-urlencoded)
// Passing the dictionary to the constructor handles the conversion
using var content = new FormUrlEncodedContent(parameters);
Console.WriteLine("Sending POST data...");
// 3. Execute POST request
using var response = await _httpClient.PostAsync(url, content);
// Verify status code (throws exception on failure)
response.EnsureSuccessStatusCode();
// 4. Display results
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("\n--- Response from Server ---");
Console.WriteLine(responseBody);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Communication Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Execution Result Example (Response from httpbin.org)
--- Response from Server ---
{
"form": {
"comment": "C# & .NET",
"encode": "UTF-8",
"keyword": "network",
"maxsize": "20"
},
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
...
},
...
}
Customization Points
- Collection Initializer: Using C# collection initializers makes the definition of key-value pairs concise.
- Sending Lists: To send multiple values for the same key (e.g.,
tag=csharp&tag=programming), useList<KeyValuePair<string, string>>instead of aDictionary.
var multiValues = new List<KeyValuePair<string, string>>
{
new("tag", "csharp"),
new("tag", "programming")
};
using var content = new FormUrlEncodedContent(multiValues);
Important Notes
- Data Size: Because
FormUrlEncodedContentconverts all data into a single URL-encoded string, it is not suitable for binary data (like images) or extremely large text. UseMultipartFormDataContentfor those scenarios. - Character Encoding: Data is encoded in UTF-8 by default. If sending to legacy systems (e.g., Shift-JIS), you must manually create a
ByteArrayContentwith the pre-encoded byte array.
Advanced Application
Checking Encoded Content
You can verify the exact string being sent to the server for debugging purposes.
using var content = new FormUrlEncodedContent(parameters);
// Read as string for debugging
string encodedString = await content.ReadAsStringAsync();
Console.WriteLine(encodedString);
// Example output: keyword=network&encode=UTF-8&maxsize=20&comment=C%23+%26+.NET
Conclusion
FormUrlEncodedContent is the standard approach for simulating web form submissions or interacting with REST APIs that require application/x-www-form-urlencoded. By simply providing key-value pairs in a collection, you can delegate the complex URL encoding and Content-Type header management to the library, ensuring a safe and clean implementation.
