我可能错过了一些非常简单的东西,但我就是找不到它。
我正在使用的 API 要求包含 Content-Type header ,即使使用 GET 也是如此。
我正在努力将 header 添加到我的请求中。
这是构建 httpclient 的代码:
public static async Task<HttpClient> Authenticate(string baseUrl, string clientId, string clientSecret)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
string toBeHashed = $"client_id={clientId}&client_secret={clientSecret}";
string hashed = sha256_hash(toBeHashed);
AuthRequest request = new AuthRequest
{
client_id = clientId,
hash = hashed
};
StringContentWithoutCharset body = new StringContentWithoutCharset(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync($"{baseUrl}authenticate", body);
AuthResponse result = await JsonSerializer.DeserializeAsync<AuthResponse>(await response.Content.ReadAsStreamAsync());
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.data.token);
return httpClient;
}
这里有 2 种不同的 GET 调用尝试。
当我查看 Fiddler 时,标题中缺少 Content-Type:
public class Functions
{
private HttpClient _httpClient;
private readonly string _baseUrl;
public Functions(string baseUrl, string clientId, string clientSecret)
{
_httpClient = Helpers.Authenticate(baseUrl, clientId, clientSecret).Result;
_baseUrl = baseUrl;
}
public async Task ProductList()
{
// this doesn't work
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}products");
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response1 = await _httpClient.SendAsync(request);
ProductList result1 = await JsonSerializer.DeserializeAsync<ProductList>(await response1.Content.ReadAsStreamAsync());
// nor does this
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response = await _httpClient.GetAsync($"{_baseUrl}products");
ProductList result2 = await JsonSerializer.DeserializeAsync<ProductList>(await response.Content.ReadAsStreamAsync());
}
}
任何帮助将不胜感激。
最佳答案
重新发布我的评论作为答案,以便对遇到同样问题的每个人都有帮助。
正如 godot 指出的那样,您不能使用 Content-Type
作为请求 header ,因为就 .NET 而言,事实并非如此。然而,它也是一个“内容 header ”(从技术上讲,它是一个请求 header )。内容 header 对于 POST
和 PUT
请求完全有效。因此,作为一个 hacky 解决方案(GET
请求不应包含内容),您可以添加以下行:
request.Content = new StringContent("", Encoding.UTF8, "application/json");
这会添加一个空的StringRequest
,并且作为第三个参数,您实际上可以指定Content-Type
。
关于c# - .Net Core 3.1 HttpClient headers.TryAddWithoutValidation 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64119750/