gpt4 book ai didi

c# - 使用 httpClient.GetAsync 时添加 header

转载 作者:IT王子 更新时间:2023-10-29 03:35:46 26 4
gpt4 key购买 nike

我正在 Windows 应用商店应用程序项目中实现其他同事使用 Apiary.io 制作的 API。

他们展示了我必须实现的方法示例:

var baseAddress = new Uri("https://private-a8014-xxxxxx.apiary-mock.com/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{
using (var response = await httpClient.GetAsync("user/list{?organizationId}"))
{
string responseData = await response.Content.ReadAsStringAsync();
}
}

在这个和其他一些方法中,我需要一个带有我之前获得的 token 的 header 。

这是一张 Postman(chrome 扩展)的图像,其中包含我正在谈论的标题: enter image description here

如何将授权 header 添加到请求中?

最佳答案

后来的回答,但是因为没有人给出这个解决方案...

如果您不想通过将 header 添加到 DefaultRequestHeaders 来在 HttpClient 实例上设置 header ,您可以为每个请求设置 header .

但是您将不得不使用 SendAsync() 方法。

如果您想重用HttpClient,这是正确的解决方案——这是一个很好的实践

像这样使用它:

using (var requestMessage =
new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", your_token);

await httpClient.SendAsync(requestMessage);
}

关于c# - 使用 httpClient.GetAsync 时添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29801195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com