将curl命令转换为.NET http请求

时间:2014-07-16 19:02:06

标签: c# .net rest curl dotnet-httpclient

有人可以帮我把这个curl命令转换成.NET中的HttpClient / HttpRequestMessage格式吗?

curl https://someapi.com/ID \
-H "Authorization: Bearer ACCESS_TOKEN" \
-d '{"name":"test name"}' \
-X PUT

到目前为止我所拥有的是这一点,但似乎并不正确:

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 个答案:

答案 0 :(得分:2)

修改 此示例使用Json.NET将字符串序列化为json格式

尝试:

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