8.18使用 LoadIntoBufferAsync 缓存响应内容

创建于 2026 年 8 月 18 日约 1 分钟读完

在发送 HTTP 远程请求时,默认情况下响应内容以流的形式返回,只能被读取一次。若您需要在多个地方重复读取响应内容(例如同时进行日志记录、内容校验和业务处理),直接读取流会导致后续读取为空或异常。

此时,可以调用 HttpContent.LoadIntoBufferAsync() 方法,将响应内容缓冲到内存中,从而实现后续重复读取

cs
var response = await httpRemoteService.GetAsync("https://furion.net/");// 将响应内容加载到内存缓冲区await response.Content.LoadIntoBufferAsync();// 现在可以多次读取响应内容var content1 = await response.Content.ReadAsStringAsync();var content2 = await response.Content.ReadAsStringAsync();