You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:HttpClient.GetByteArrayAsync(request)调用失败,同步方式可正常运行

问题分析与解决方案

首先,你的代码存在两个关键问题导致异步调用失败:

  • HttpClient.GetByteArrayAsync() 没有接受 HttpRequestMessage 的重载,这行代码不符合API规范,无法正确执行。
  • 如果包含这段代码的方法未标记 async,使用 await 会直接出现编译错误或运行异常。

以下是修正后的异步代码:

// 确保方法标记为async,返回类型为Task<IActionResult>
public async Task<IActionResult> YourMethodName()
{
    var handler = new HttpClientHandler();
    handler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true;
    using (var httpClient = new HttpClient(handler))
    {
        using (var request = new HttpRequestMessage(HttpMethod.Get, "https://adr.adr"))
        {
            request.Headers.TryAddWithoutValidation("Authorization", "HCP user:pass");

            // 用SendAsync发送自定义HttpRequestMessage
            var response = await httpClient.SendAsync(request);
            // 可选:确保响应成功,失败时抛出异常,便于排查问题
            response.EnsureSuccessStatusCode();
            
            // 异步读取字节数组
            var responseBytes = await response.Content.ReadAsByteArrayAsync();
            var responseString = Encoding.Unicode.GetString(responseBytes, 0, responseBytes.Length - 1);
            return Ok(responseString);
        }
    }
}

关键修正说明

  • 替换错误的 GetByteArrayAsync(request) 调用:先通过 SendAsync(request) 发送自定义请求,再用 response.Content.ReadAsByteArrayAsync() 异步读取响应内容。
  • 方法必须标记 async,返回类型改为 Task<IActionResult>,这是使用 await 的必要前提。
  • 添加 response.EnsureSuccessStatusCode() 可以在请求失败时主动抛出异常,方便定位错误;如果不需要自动抛出,也可以自行判断 response.IsSuccessStatusCode 处理失败场景。

同步方式能运行是因为绕开了错误的API调用逻辑,但异步场景必须遵循正确的HttpClient调用流程。

内容的提问来源于stack exchange,提问作者apkp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:02:33