英文:
Change response.Content.ReadAsStringAsync to await httpClient.GetByteArrayAsync
问题
以下是您的代码的翻译部分:
我有一个代码问题:
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true;
使用 (var httpClient = new HttpClient(handler))
{
使用 (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://adr.adr"))
{
request.Headers.TryAddWithoutValidation("Authorization", "HCP user:pass");
var response = await httpClient.GetByteArrayAsync(request);
var responseString = Encoding.Unicode.GetString(response, 0, response.Length - 1);
返回 Ok(responseString);
}
}
请注意,由于您要求仅返回翻译的部分,我已删除问题陈述和示例代码的代码部分,只包括您的请求和注释。如果您需要任何进一步的帮助或解释,请随时提问。
英文:
I have problem with code:
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true;
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://adr.adr"))
{
request.Headers.TryAddWithoutValidation("Authorization", "HCP user:pass");
var response = await httpClient.GetByteArrayAsync(request);
var responseString = Encoding.Unicode.GetString(response, 0, response.Length - 1);
return Ok(responseString);
}
}
Please help, this line not works, i tried other examples but only this works (but with response.Content.ReadAsStringAsync().Result;
):
var response = await httpClient.GetByteArrayAsync(request);
答案1
得分: 0
GetByteArrayAsync
不具备接受 HttpRequestMessage
的任何重载,它期望一个 URL,可以是 string
或 Uri
类型:https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getbytearrayasync?view=net-7.0
尝试这样做:
using (var httpClient = new HttpClient(handler))
{
httpClient.DefaultRequestHeaders.Add("Authorization", "HCP user:pass");
var response = await httpClient.GetByteArrayAsync("https://adr.adr");
var responseString = Encoding.Unicode.GetString(response, 0, response.Length - 1);
return Ok(responseString);
}
然而,你可能不希望在每个请求中都创建一个新的 HttpClient
,我建议改用注入 IHttpClientFactory
:https://stackoverflow.com/a/59281244/5369074
英文:
GetByteArrayAsync
doesn't have any overloads which accept an HttpRequestMessage - it expects a url as either a string
or a Uri
: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getbytearrayasync?view=net-7.0
Try this instead:
using (var httpClient = new HttpClient(handler))
{
httpClient.DefaultRequestHeaders.Add("Authorization", "HCP user:pass");
var response = await httpClient.GetByteArrayAsync("https://adr.adr");
var responseString = Encoding.Unicode.GetString(response, 0, response.Length - 1);
return Ok(responseString);
}
You probably don't want to be creating a new HttpClient
on each request though, I'd suggest injecting IHttpClientFactory
instead: https://stackoverflow.com/a/59281244/5369074
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论