How do i convert this curl commant to c#? - c#

I am struggeling to convert a curl command to functioning c# code.
curl "https://MY_SERVER/api/3.4/sites/site-id/workbooks" -X POST -H "X-Tableau-Auth:credentials token" -H "Content-Type: multipart/mixed;" -F "request_payload=#publish-workbook.xml" -F "tableau_workbook=#MY_WORKBOOK.twbx"
Can anyone help?

Using curl to C# convertor I've got this result:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://my_server/api/3.4/sites/site-id/workbooks"))
{
request.Headers.TryAddWithoutValidation("X-Tableau-Auth", "credentials token");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("publish-workbook.xml")),
"request_payload", Path.GetFileName("publish-workbook.xml"));
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("MY_WORKBOOK.twbx")),
"tableau_workbook", Path.GetFileName("MY_WORKBOOK.twbx"));
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}
In "Path.GetFileName()" you should change the file path.

use some online converter or make custom one. its on you.
C# of your curl below:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://my_server/api/3.4/sites/site-id/workbooks"))
{
request.Headers.TryAddWithoutValidation("X-Tableau-Auth", "credentials token");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("publish-workbook.xml")), "request_payload", Path.GetFileName("publish-workbook.xml"));
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("MY_WORKBOOK.twbx")), "tableau_workbook", Path.GetFileName("MY_WORKBOOK.twbx"));
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}

Related

Pass Files in C# HttpClient Post request

I am writing code in C# to consume POST API that accepts form-body with the following parameters.
Files[Array] (User can send multiple files in request)
TemplateId[Int]
Also, I need to pass the bearer AuthToken as a header in the HTTP client Post Request.
I need some help writing the HTTP request with the above form data.
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, $" {_apiBaseUri}/{route}");
requestMessage.Headers.Authorization = new AuthenticationHeaderValue($"Bearer {authToken}");
var pdfFiles = Directory.GetFiles($"C:\\files", "*.pdf");
foreach (var filename in pdfFiles)
{
// create array[] of each File and add them to the form data request
}
// Add TemplateId in the form data request
}
postman request
swagger request
you can add files with 'MultipartFormDataContent'.
private static async Task UploadSampleFile()
{
var client = new HttpClient
{
BaseAddress = new("https://localhost:5001")
};
await using var stream = System.IO.File.OpenRead("./Test.txt");
using var request = new HttpRequestMessage(HttpMethod.Post, "file");
using var content = new MultipartFormDataContent
{
{ new StreamContent(stream), "file", "Test.txt" }
};
request.Content = content;
await client.SendAsync(request);
}
for more: https://brokul.dev/sending-files-and-additional-data-using-httpclient-in-net-core
The Below Code change worked for me,
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), _apiBaseUri))
{
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {authToken}");
var pdfFiles = Directory.GetFiles($"C:\\test", "*.pdf");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("100"), "templateId");
foreach (var filename in pdfFiles)
{
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(filename)), "files", Path.GetFileName(filename));
}
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}

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 ?
You can use this package to convert HTTPClient to curl:
First install NuGet package:
dotnet add package HttpClientToCurl
Example:
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");
Get curl from request
httpClient.GenerateCurlInConsole(httpRequestMessage, requestUri ); // Generate curl in console
httpClient.GenerateCurlInFile(httpRequestMessage, requestUri ); // Generate curl in file
HTTP call
// Call PostAsync => await client.PostAsync(requestUri, httpRequest.Content);
To get more information see the repo GitHub docs

400 Bad Request when trying to submit a POST request to upload artifacts in nexus

I am trying to upload artifacts using .net HttpClient but getting 400 Bad Request. I am giving a zip file in the request content. This is my code.
I was able to do this via the curl command and transformed the curl command to.net code.
curl -v -F r=release-folder -F hasPom=false -F g=release-group -F a=artifact-01 -F v=1.0 -F p=zip -F file=#P:\test.zip -u username:password https://localhost:80/nexus/service/local/artifact/maven/content --insecure
Please help pinpoint what I am doing wrong here.
var handler = new HttpClientHandler();
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"),
ConfigurationManager.AppSettings["nexusUrl"]))
{
var base64authorization = Convert.ToBase64String
(Encoding.ASCII.GetBytes("username:password"));
request.Headers.TryAddWithoutValidation("Authorization",
$"Basic
{base64authorization}");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent
(ConfigurationManager.AppSettings["repository"]), "r");
multipartContent.Add(new StringContent("false"), "hasPom");
multipartContent.Add(new StringContent
(ConfigurationManager.AppSettings["group"]), "g");
multipartContent.Add(new StringContent("artifact-01), "a");
multipartContent.Add(new StringContent("1.0"), "v");
multipartContent.Add(new StringContent("zip"), "p");
multipartContent.Add(new StringContent("zip"), "e");
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes
(#"P:\test.zip")), "file", Path.GetFileName(#"P:\test.zip"));
request.Content = multipartContent;
var response = await httpClient.SendAsync
(request);
}
}

How to convert curl request to HttpClient having --resolve

I have a following curl request
curl -X POST -D- --insecure -H "ApiKey: $api_key" https://api.myapi.com/service/12345/purge/12345--resolve [http://api.myapi.com:443:11.112.121.194/]api.myapi.com:443:11.112.121.194
I want to convert that over to HttpClient.
var baseUrl = "https://api.myapi.com";
HttpClient httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("ApiKey", "api_key");
var request = new HttpRequestMessage(HttpMethod.Post, $"service/{12345}/purge/{12345}");
request.Content = new StringContent(null, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
How do I add --resolve parameter to HttpRequest?

C# CURL POST(Content-Type, Hash key)

I am currently trying to send POST request in C# (API), but I have some troubles with Content Type and Authorization, because its in format apiHash, apiKey.
Curl example:
curl -i -XPOST https://sandboxapi.g2a.com/v1/order \
-H "Authorization: qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875" \
-H 'Content-Type: application/json' \
-d '{"product_id": "10000027819004", "max_price": 45.0}'
Documentation for API:
https://www.g2a.com/integration-api/documentation/#api-Orders-AddOrder
And this is my code so far:
private static readonly HttpClient client = new HttpClient();
public async Task < string > makeRequest() {
var values = new Dictionary < string,
string > {
{
"product_id",
"10000027819004"
},
{
"max_price",
"45.0"
}
};
var content = new FormUrlEncodedContent(values);
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("qdaiciDiyMaTjxMt", "74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
client.DefaultRequestHeaders.Authorization = authHeaders;
var response = await client.PostAsync("https://sandboxapi.g2a.com/v1/order", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
I tried multiple solutions, but I seem to be unable to have it all correct together(Content-Type, Authorization and parameters).
You must set the content type like this :
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
This will solve the issue.
You are sending FormUrlEncodedContent which is not JSON while the curl example is sending JSON.
Refactor your method to use actual serialized JSON string in a StringContent with proper content type set.
public async Task<string> makeRequest() {
var values = new {
product_id = "10000027819004",
max_price = 45.0
};
//-d '{"product_id": "10000027819004", "max_price": 45.0}'
var json = JsonConvert.SerializeObject(values); //using Json.Net
var content = new StringContent(json);
var auth = "qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875";
//-H "Authorization: qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875" \
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
//-H 'Content-Type: application/json' \
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var response = await client.PostAsync("https://sandboxapi.g2a.com/v1/order", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}

Categories