Skip to content

HttpRequestMessage Examples

mozhganEtaati edited this page Oct 10, 2025 · 9 revisions

💡 The examples below use POST requests via the HttpRequestMessage extension.

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 = newStringContent(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 curl = httpRequestMessage.GenerateCurlInString(baseAddress);
        Console.WriteLine("Generated curl command:\n");
        Console.WriteLine(curl);
    }
}

CURL in File

If the path variable is null or empty, then the file is created in yourProjectPath/bin/Debug/netx.0

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 client = 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 request = new(HttpMethod.Post, requestUri);

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

            // Set the request content with the requestBody 
            request.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

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

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

            // 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}");
        }
    }
}

CURL in Console

using System.Text;
using HttpClientToCurl;

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

        // Create an instance of HttpClient
        HttpClient client = 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 request = new(HttpMethod.Post, requestUri);

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

            // Set the request content with the requestBody 
            request.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

            request.GenerateCurlInConsole(baseAddress, config => { config.EnableCodeBeautification = true; });

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

            // 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}");
        }
    }
}
Clone this wiki locally