Converting a curl command to a .NET http request - c#

Could someone please help me convert this curl command into a HttpClient/HttpRequestMessage format in .NET?
curl https://someapi.com/ID \
-H "Authorization: Bearer ACCESS_TOKEN" \
-d '{"name":"test name"}' \
-X PUT
What I have so far is this, but it doesn't seem to be right:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Put, url);
request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
request.Properties.Add("name", "test name");
return await client.SendAsync(request).ConfigureAwait(false);

Edit:
This example uses Json.NET to serialize the string to a json format
Try:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var anonString = new { name = "test name" };
var json = JsonConvert.SerializeObject(anonString);
await client.PutAsync("URL", new StringContent(json)).ConfigureAwait(false);

Related

Creating Postman request in C#

I am able to make the following request in Postman but not able to in C#. I'm guessing it's due to the json but tried a few different ways and still nothing.
Postman:
curl --location --request POST 'https://login.sandbox.payoneer.com/api/v2/oauth2/token' \
--header 'Authorization: Basic *ENCRYPTEDPASSCODE FROM ClientID & Secret*' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'scope=read write'
My Code returns text "ErrorParams":null:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token");
var authString = $"{clientID}:{secret}";
var encodedString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(authString));
request.Headers.Add("Authorization", $"Basic {encodedString}");
string json = JsonConvert.SerializeObject(new
{
grant_type = "client_credentials",
scope = "read write"
});
request.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();
return responseText;
If you need to set the content as application/x-www-form-urlencoded then use FormUrlEncodedContent
var dict = new Dictionary<string, string>();
dict.Add("grant_type", "client_credentials");
dict.Add("scope", "read write");
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token") { Content = new FormUrlEncodedContent(dict) };
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();
If you are serializing the request body to JSON, then you need to set the Content-Type as application/json
request.Headers.Add("Content-Type", "application/json");

Http Request to download file from remote server

I am trying to translate the following curl command
curl --location --request GET "https://xxx.xxxx.xxx/artifacts?session=016e1f70-d9da-41bf-b93d-80e281236c46&path=/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log" -H "Authorization:Bearer xxxx" -H "Accept:application/json" --output C:\Temp\Game.log
To C# code and I have the following
string SessionId = "016e1f70-d9da-41bf-b93d-80e281236c46";
string Token = "xxxx";
string FilePath = "/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log";
string Endpoint = string.Format("https://xxx.xxxx.xxx/artifacts?session={0}&path={1}", SessionId, FilePath);
HttpRequestMessage HttpRequestMsg = new HttpRequestMessage();
HttpRequestMsg.RequestUri = new Uri(Endpoint);
HttpRequestMsg.Method = HttpMethod.Get;
HttpRequestMsg.Headers.Add("Accept", "application/json");
HttpRequestMsg.Headers.Add("Authorization", string.Format("Bearer {0}", Token));
HttpRequestMsg.Content = new StringContent(string.Format("--output {0}", OutFilePath), Encoding.UTF8, "application/json");
using (HttpClient Client = new HttpClient())
{
var HttpResponseTask = Client.SendAsync(HttpRequestMsg);
}
But it gives me the following exception info
Cannot send a content-body with this verb-type.
--location and --output are not C# supported options
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://xxx.xxxx.xxx/artifacts?session=016e1f70-d9da-41bf-b93d-80e281236c46&path=/home/gauntlet_gameye/LinuxServer/Game/Saved/Logs/Game.log");
request.Headers.Add("Authorization", "Bearer xxxx");
request.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Source: Convert curl commands to C#

How to send http from with POST method without URLEncoding in unity?

I'm trying to send some data to a server using POST in unity but because unity url-encodes the data when using UnityWebRequest.Post() I'm getting 404 error from server, so I want to constract request myself however I'm still getting same error.
the curl request is something like this:
curl -X 'POST' \
'https://[server url].com/api/v1/client/match/195' \
-H 'accept: application/json' \
-H 'Authorization: Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0...' \
-H 'Content-Type: multipart/form-data' \
-F 'Data=1647396005200|7Q3E1dEzFnVDEdRtZbPEjBXkde+MGaWdzk9WJtmZF90='
I can send this data with .net without problem:
private static async Task SendRequestAsync(string url)
{
string Json = $"{{\"Score\":10,\"Time\":10}}";
string dataToSend = EncryptData(Json);
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "Data", dataToSend }
};
client.DefaultRequestHeaders.Add("accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", AccessToken);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
print(responseString);
}
But I want to use UnityWebRequest to archive the same result but I'm getting server error. this is the code for UnityWebRequest.
string Json = $"{{\"Score\":10,\"Time\":10}}";
var dataToSend = EncryptData(Json);
WWWForm form = new WWWForm();
form.AddField("Data", dataToSend, Encoding.UTF8);
var downloadHandlerRaw = new DownloadHandlerBuffer();
//var data = Encoding.UTF8.GetBytes(dataToSend);
request = new UnityWebRequest();
request.url = url;
request.method = UnityWebRequest.kHttpVerbPOST;
request.uploadHandler = new UploadHandlerRaw(form.data);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("accept", "application/json");
request.SetRequestHeader("Authorization", AccessToken);
request.SetRequestHeader("Content-Type", "multipart/form-data");
I don't know what I'm doing wrong, I have tried so many things but I can't make it work. how can I fix it? any help is appreciated, thanks.

Getting an error message saying missing parameter in StringContent, but it is present?

There is a code like this:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
request.Content = new StringContent("{" +
$"\"grant_type\":\"authorization_code\"," +
$"\"client_id\":\"*****\"," +
$"\"client_secret\":\"****\"," +
$"\"code\":\"{autorizationCode}\"," +
$"\"redirect_uri\":\"urn:ietf:wg:oauth:2.0:oob\"" +
"}", Encoding.UTF8);
var response = await client.SendAsync(request);
Token = response.Content.ReadAsStringAsync().Result.ToString();
}
When I send a request, it gives me an error - "{"error":"invalid_request","error_description":"Missing required parameter: grant_type."}", but grant_type is present.
The request on the site looks like this:
curl -X POST "https://site/oauth/token" \
-H "User-Agent: APPLICATION_NAME" \
-F grant_type="authorization_code" \
-F client_id="CLIENT_ID" \
-F client_secret="CLIENT_SECRET" \
-F code="AUTORIZATION_CODE" \
-F redirect_uri="REDIRECT_URI"
Why is he giving this error? How can I fix it?
The CURL-Parameter -F represents form content, not JSON-Content.
If you want to send FormContent, you cannot use StringContent, you need to use FormUrlEncodedContent, like this:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
request.Content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>>() {
new KeyValuePair<string,string>("grant_type", "authorization_code"),
new KeyValuePair<string,string>("client_id", "*****"),
new KeyValuePair<string,string>("client_secret", "*****"),
new KeyValuePair<string,string>("code", $"{autorizationCode}"),
new KeyValuePair<string,string>("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")
} );
var response = await client.SendAsync(request);
Token = response.Content.ReadAsStringAsync().Result.ToString();
}
/Edit: Regarding your comment, your endpoint also supports JSON and you missed the content-type. I'll leave this here in case anyone gets into the problem with an exact CURL-Request like you mentioned.

How to construct HttpClient POST Request with form-data in C#?

I am having issues constructing the POST request with form-data in C# using HTTPClient. i tried multiple approaches but nothing seems to work. Can you please help what I am missing?
Please be informed, the SWAGGER POST is working fine and based on that I am trying to construct the request.
The API parameters
rPath* string
(formData)
nName* string
(formData)
nFile string
(formData)
type* string
(formData)
zFile file
file
The working swagger POST
curl -X POST "http://localhost:8888/server/api/v1.0/createfolder" -H "accept: text/plain; charset=UTF-8" -H "authorization: Basic XXXXXXX" -H "Content-Type: multipart/form-data" -F "rPath=/RootFolder/" -F "nName=testing" -F "type=Folder"
The Fiddler request header of the SWAGGER POST (This is working).
static void Main(string[] args)
{
var formData = new MultipartFormDataContent();
HttpContent content = new FormUrlEncodedContent (new[]
{
new KeyValuePair<string, string>("rPath", "/RootFolder/"),
new KeyValuePair<string, string>("nName", "TestFolder"),
new KeyValuePair<string, string>("type", "Folder")
});
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
formData.Add(content);
var url = "http://localhost:8888/server/api/v1.0/createfolder";
HttpResponseMessage response = PostRoot(formData, url);
}
static HttpResponseMessage PostRoot(HttpContent content, string webMethod)
{
HttpResponseMessage response = new HttpResponseMessage();
using (var client = new HttpClient() { })
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "xxxxxxx=");
response = client.PostAsync(webMethod, content).Result;
}
return response;
}
Here's an example of how to send multi part form data:
var client = new HttpClient();
var baseUrl = "https://someurl";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
var formContent = new MultipartFormDataContent
{
{new StringContent("ParamValue1"),"ParamName1"},
{new StringContent("ParamValue2"),"ParamName2"},
{new StringContent("ParamValue2"),"ParamName3"},
};
var response = client.PostAsync(baseUrl, formContent).Result;
response.EnsureSuccessStatusCode();
var result = string.Empty;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
return result;

Categories

Resources