Skip to content

HttpRequestMessage Examples

Mozhgan Etaati edited this page Nov 13, 2025 · 9 revisions

💡 The examples below use POST requests via the HttpRequestMessage extension.You can see more samples in the Functional Tests Directory. More Samples

CURL in String

using System;
using System.Net.Http;
using System.Text;
using HttpClientToCurl;

class Program
{
    static void Main()
    {
        string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";

        var requestUri = "api/test";
        var httpRequestMessage = 
                 new HttpRequestMessage(HttpMethod.Post, requestUri) 
                { Content = new StringContent(requestBody, Encoding.UTF8,MediaTypeNames.Application.Json) };
        httpRequestMessage.Headers.Add("Authorization", "Bearer 4797c126-3f8a-454a-aff1-96c0220dae61");
        var baseAddress = new Uri("http://localhost:1213/v1/");
        string curlResult = httpRequestMessage.GenerateCurlInString(baseAddress);
        Console.WriteLine("Generated curl command:\n");
        Console.WriteLine(curlResult);
    }
}

✅ Output:

curl -X POST 'http://localhost:1213/v1/api/test' -H 'Authorization: Bearer 4797c126-3f8a-454a-aff1-96c0220dae61' 
-H 'Content-Type: application/json; charset=utf-8' -d '{"name":"sara","requestId":10001001,"amount":20000}'

CURL in File

In the file config option, if the path variable is null or empty, then the file is created in yourProjectPath/bin/Debug/netx.0 And if the filename variable is null or empty, then the current date will be set for it with this format: yyyyMMdd

using System.Text;
using HttpClientToCurl;

class Program
{
    static async Task Main()
    {
        var requestUri = "api/test";

        // Create an instance of HttpClient
        HttpClient httpClient = new();
        var baseAddress = new Uri("http://localhost:1213/v1/");

        try
        {
            // Create a sample Serialized JSON 
            string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";

            // Create HttpRequestMessage with the POST verb
            HttpRequestMessage httpRequestMessage = new(HttpMethod.Post, requestUri);

            // Set up the request headers
            httpRequestMessage.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers

            // Set the request content with the requestBody 
            httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

            // Log the curl command for debugging or testing.
            // This generates a curl command that can be imported into Postman.
            // Use it to check and compare against all the requirements.
            // Config is the second, and an optional parameter

            httpRequestMessage.GenerateCurlInFile(baseAddress, config =>
            {
                // Customize file configuration if needed
                config.TurnOn = true; // Enable generating curl command to file
                config.Filename = "curl_commands"; // Specify the file name
                config.Path = "C:\\Path\\To\\Directory"; // Specify the directory path
                config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
            });

            httpClient.BaseAddress = baseAddress;
            // Send the request
            HttpResponseMessage response = await httpClient.SendAsync(httpRequestMessage);

            // Check if the request was successful (status code 200-299)
            if (response.IsSuccessStatusCode)
            {
                // Read and print the response content as a string
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response from the API:\n" + responseBody);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex.Message}");
        }
    }
}

✅ Output:

curl -X POST 'http://localhost:1213/v1/api/test' -H 'Authorization: Bearer YourAccessToken' 
-H 'Content-Type: application/json; charset=utf-8' -d '{"name":"sara","requestId":10001001,"amount":20000}' 

CURL in Console

using System.Text;
using HttpClientToCurl;

class Program
{
    static async Task Main()
    {
        var requestUri = "api/test";

        // Create an instance of HttpClient
        HttpClient httpClient = new();
        var baseAddress = new Uri("http://localhost:1213/v1/");

        try
        {
            // Create a sample Serialized JSON 
            string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";

            // Create HttpRequestMessage with the POST verb
            HttpRequestMessage httpRequestMessage = new(HttpMethod.Post, requestUri);

            // Set up the request headers
            httpRequestMessage.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers

            // Set the request content with the requestBody 
            httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

            // Log the curl command for debugging or testing.
            // This generates a curl command that can be imported into Postman.
            // Use it to check and compare against all the requirements.
            // You can customize the console configuration if needed
            // Config is the Second and an optional parameter. 

            httpRequestMessage.GenerateCurlInConsole(baseAddress, config =>
            {
                config.TurnOn = true; // Enable generating curl command to console
                config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
                config.EnableCodeBeautification = false;
            });

            httpClient.BaseAddress = baseAddress;
            // Send the request
            HttpResponseMessage response = await httpClient.SendAsync(httpRequestMessage);

            // Check if the request was successful (status code 200-299)
            if (response.IsSuccessStatusCode)
            {
                // Read and print the response content as a string
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response from the API:\n" + responseBody);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception: {ex.Message}");
        }
    }
}

✅ Output:

curl -X POST 'http://localhost:1213/v1/api/test' -H 'Authorization: Bearer YourAccessToken' 
-H 'Content-Type: application/json; charset=utf-8' -d '{"name":"sara","requestId":10001001,"amount":20000}'
Clone this wiki locally