0

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

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I tried this but it comes back with a "bad request" error.
@Prabhu of course, your curl code posts json data, but this answer tries to send url-encoded data.
I looked up the curl -d and it said: (HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.