如何在 .NET Core 中使用 HttpClient 传递 header 和参数

How can I pass header and parameter with HttpClient in .NET Core

这是我使用 RestSharp 库的代码:

var client = new RestClient("https://example.com/api");
client.Timeout = -1;

var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer token...");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody);

IRestResponse response = await client.ExecuteAsync(request);
// Console.WriteLine(response.Content);
// var res = response.Content;

如何使用最佳实践将其转换为 HttpClient

你可以使用这个:

var client = new HttpClient()
{
    BaseAddress = new Uri("https://example.com"),
    Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds
};

client.DefaultRequestHeaders.Add("Authorization", "Bearer token...");
var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain");

var response = await client.PostAsync("api", body);

var responseString = await response.Content.ReadAsStringAsync();

为了以正确的方式使用 HttpClient,我强烈建议您查看此 link