HttpRequestMessage Class

Namespace: System.Net.Http
Represents an HTTP request message.

The HttpRequestMessage class represents an HTTP request message. It is used to send HTTP requests to a server and includes properties for the request method, URI, headers, and content.

Constructors
Properties
Methods
Examples

Here's a basic example of how to create and use an HttpRequestMessage:


using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Example
{
    public static async Task MakeRequest()
    {
        using (var request = new HttpRequestMessage(HttpMethod.Get, "https://www.example.com/api/data"))
        {
            // Add custom headers if needed
            request.Headers.Add("Accept", "application/json");

            // Optionally add content for POST, PUT, etc.
            // request.Content = new StringContent("{\"key\": \"value\"}", System.Text.Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                HttpResponseMessage response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not success

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
}