HttpRequestMessage.Content Property
Gets or sets the HTTP content of the request.
public HttpContent Content { get; set; }
Remarks
The Content property of the HttpRequestMessage class represents the body of the HTTP request.
This property is of type HttpContent, which is an abstract base class.
You will typically use derived classes of HttpContent such as StringContent,
ByteArrayContent, or StreamContent to represent the request body.
When sending a request using HttpClient, the Content property is serialized
and sent as the request body. For example, you might set the Content to a StringContent
object containing JSON data for a POST or PUT request.
Example
The following C# code snippet demonstrates how to set the Content property of an HttpRequestMessage
with JSON data.
// Create an HttpRequestMessage with a POST method
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.example.com/items");
// Prepare the JSON payload
var jsonPayload = @"
{
""name"": ""New Item"",
""value"": 123
}";
// Set the Content property using StringContent
request.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
// Use HttpClient to send the request (not shown here for brevity)
// using (HttpClient client = new HttpClient()) { ... }