Prabhu
Prabhu

Reputation: 13335

Converting a curl command to a .NET http request

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

Upvotes: 0

Views: 3628

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

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

Upvotes: 2

Related Questions