Skip to content

HttpClient Examples

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

CURL in String

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

Using HttpRequestMessage

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

        using var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");

        string curlResult = httpClient.GenerateCurlInString(httpRequestMessage);
        Console.WriteLine("Generated curl command:\n");
        Console.WriteLine(curlResult);

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

✅ 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}'

Without HttpRequestMessage

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

class Program
{
    static void Main()
    {
     var requestObject = new { name = "sara", requestId = 10001001, amount = 20000 };

     JsonContent jsonContent = JsonContent.Create(requestObject);

     var requestUri = "api/test";
     HttpRequestHeaders httpRequestHeaders = new HttpRequestMessage().Headers;
     httpRequestHeaders.Add("Authorization", "Bearer 4797c126-3f8a-454a-aff1-96c0220dae61");

     using var httpClient = new HttpClient();
     httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");

     string curlResult = httpClient.GenerateCurlInString(
     HttpMethod.Post, requestUri, httpRequestHeaders, jsonContent);
        Console.WriteLine("Generated curl command:\n");
        Console.WriteLine(curlResult);

    // Send the request
    HttpResponseMessage response = await httpClient.PostAsync(requestUri, jsonContent);
    }
}

✅ 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}'

Without HttpRequestMessage and RequestUri

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

class Program
{
    static void Main()
    {
     var requestObject = new { name = "sara", requestId = 10001001, amount = 20000, };

     JsonContent jsonContent = JsonContent.Create(requestObject);

     HttpRequestHeaders httpRequestHeaders = new HttpRequestMessage().Headers;
     httpRequestHeaders.Add("Authorization", "Bearer 4797c126-3f8a-454a-aff1-96c0220dae61");

     using var httpClient = new HttpClient();
     httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");


     string curlResult = httpClient.GenerateCurlInString(
                            httpMethod: HttpMethod.Post, 
                            httpRequestHeaders: httpRequestHeaders, 
                            httpContent: jsonContent,
                            requestUri: string.Empty);

     Console.WriteLine("Generated curl command:\n");
     Console.WriteLine(curlResult);

     // Send the request
     HttpResponseMessage response = await httpClient.PostAsync(string.Empty, jsonContent);
    }
}

✅ Output:

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

Without HttpRequestMessage and Headers

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

class Program
{
    static void Main()
    {
     var requestObject = new { name = "sara", requestId = 10001001, amount = 20000, };

     JsonContent jsonContent = JsonContent.Create(requestObject);

     var requestUri = "api/test";

     using var httpClient = new HttpClient();
     httpClient.BaseAddress = new Uri("http://localhost:1213/v1/");

     string curlResult = httpClient.GenerateCurlInString(
     httpMethod: HttpMethod.Post, requestUri: requestUri, httpContent: jsonContent);

     Console.WriteLine("Generated curl command:\n");
     Console.WriteLine(curlResult);

    // Send the request
    HttpResponseMessage response = await httpClient.PostAsync(requestUri, jsonContent);
    }
}

✅ Output:

curl -X POST 'http://localhost:1213/v1/api/test' -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 System.Text.Json;
using HttpClientToCurl;

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

        // Create an instance of HttpClient
        HttpClient httpClient = new();
        httpClient.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");


            // Generate a curl command and write it to a file for debugging or testing.
            // This command can be imported into Postman for checking and comparing against all the requirements.
            // Config is the second, and an optional parameter
            httpClient.GenerateCurlInFile(httpRequestMessage, 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
            });

            // 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 System.Text.Json;
using HttpClientToCurl;

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

        // Create an instance of HttpClient
        HttpClient httpClient = new();
        httpClient.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. 

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

            // 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