gpt4 book ai didi

c# - 使用 Bearer Token 在 C# 中构建 post HttpClient 请求

转载 作者:行者123 更新时间:2023-12-05 09:34:31 24 4
gpt4 key购买 nike

我并不是真正的 C# 专家,我在 C# 中有一个 httpRequest 帖子要开发,为此我创建了这个方法,它接受一个 Uri、一个对象和一个不记名 token 。

该方法旨在构建调用请求:

private HttpClient client = new HttpClient(); 
public async Task<UserResponse> CreateUser(Uri url, UserRequest userRequest, string token)
{

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");


string requestObject = JsonConvert.SerializeObject(userRequest);
Console.WriteLine("My Object: " + requestObject);
var req = new HttpRequestMessage(HttpMethod.Post, url);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
req.Content = new StringContent(
requestObject,
Encoding.UTF8,
"application/json"
);

Console.WriteLine(req.ToString());
var response = await client.SendAsync(req);

string output = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.DeserializeObject(output));

UserResponse returnValue = JsonConvert.DeserializeObject<UserResponse>(output);
return returnValue;
}

我的问题是我不确定我是否正确传递了我的 header 内容。返回响应是一条错误消息,告诉我未通过身份验证。

谢谢

最佳答案

你必须以这种方式添加 token :

var baseAddress = "http://....";
var api = ".....";
client.BaseAddress = new Uri(baseAddress);

var contentType = new MediaTypeWithQualityHeaderValue("application/json");

client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

var postData = JsonConvert.SerializeObject(userRequest);
contentData = new StringContent(postData, Encoding.UTF8, "application/json");

var response = await client.PostAsync(baseUrl + api, contentData);

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<UserResponse>(stringData);
}
else
{
}

关于c# - 使用 Bearer Token 在 C# 中构建 post HttpClient 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66545906/

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