Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert C# HttpClient to curl?

Imagine you are making a HTTP request for example (though it could be any http call):

string baseurl = LocalConfigKey.BaseUrl;
string geturl = string.Format("{0}leo-platform-api/api/v1/Orchestrator/Endpoint", baseurl);

var response = string.Empty;
using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", LocalConfigKey.APIMSubscriptionKey);
    HttpResponseMessage result = httpClient.GetAsync(geturl).GetAwaiter().GetResult();
    result.EnsureSuccessStatusCode();
    if (result.IsSuccessStatusCode)
    {
        response = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    }
}

Is it possible to generate curl out of this request that can be logged in a db etc ?

like image 840
SamuraiJack Avatar asked Oct 19 '25 20:10

SamuraiJack


1 Answers

You can use this package to convert HTTPClient to curl:

First, install the NuGet package:

dotnet add package HttpClientToCurl

Example:

1. Declare request requirements:

string requestBody = @"{ ""name"" : ""amin"",""requestId"" : ""10001000"",""amount"":10000 }";
string requestUri = "api/test";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri);
httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://localhost:1213");

2. Get curl from the request in 3 ways:

string curlScript = httpClient.GenerateCurlInString(httpRequestMessage); //Put into a variable

httpClient.GenerateCurlInConsole(httpRequestMessage); //Show in the console

httpClient.GenerateCurlInFile(httpRequestMessage); //Write in a file

3. HTTP call:

await client.PostAsync(requestUri, httpRequestMessage.Content);

To get more information see the repo GitHub docs

like image 113
Hamed Naeemaei Avatar answered Oct 22 '25 09:10

Hamed Naeemaei