.Net Core 跨API接收FileContentResult:如何将HttpResponseMessage做转换
HttpResponseMessage转FileContentResult实现方案
FileContentResult本质由三个核心属性构成:文件字节数组FileContents、媒体类型ContentType、可选下载文件名FileDownloadName,只需从HttpResponseMessage中提取对应信息即可完成转换。
基础实现代码
using Microsoft.AspNetCore.Mvc; using System.Net.Http; using System.Threading.Tasks; public async Task<IActionResult> GetProxyFile() { // 建议生产环境通过IHttpClientFactory注入HttpClient,避免套接字资源耗尽 using var httpClient = new HttpClient(); // 替换为实际源API地址 var sourceFileApiUrl = "https://your-source-api-endpoint"; HttpResponseMessage response = await httpClient.GetAsync(sourceFileApiUrl); // 校验源API请求是否成功,失败会抛出HttpRequestException response.EnsureSuccessStatusCode(); // 提取文件字节数组 byte[] fileContent = await response.Content.ReadAsByteArrayAsync(); // 提取响应Content-Type作为文件媒体类型,无匹配值时默认用二进制流类型 string contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream"; // 提取源接口指定的下载文件名,无匹配值时设置默认文件名 string downloadFileName = response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName ?? "default.file"; // 直接构造并返回FileContentResult return new FileContentResult(fileContent, contentType) { FileDownloadName = downloadFileName }; }
优化注意事项
- 若源API返回大体积文件,不建议全量读取字节数组到内存,可改用
FileStreamResult直接返回响应流,降低内存占用:Stream fileStream = await response.Content.ReadAsStreamAsync(); return new FileStreamResult(fileStream, contentType) { FileDownloadName = downloadFileName }; - 若源API需要鉴权,可在发起请求前将当前请求的鉴权头、Cookie等信息透传到
HttpClient的请求头中。 - 生产环境禁止每次请求新建
HttpClient实例,需通过依赖注入注入IHttpClientFactory创建复用实例。
内容的提问来源于stack exchange,提问作者TopBanana9000
相关产品推荐
相关产品推荐

