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

如何将第三方HttpResponseMessage中的PDF内容返回至浏览器?

问题解决:ASP.NET Core代理返回PDF时客户端收到JSON而非PDF

核心原因是ASP.NET Core中控制器直接返回HttpResponseMessage时,框架会自动将该对象序列化为JSON,而非将其内容作为原始HTTP响应发送,这就是你看到客户端收到JSON文件的根本问题。

方案1:使用FileStreamResult返回并设置inline头

这是最符合ASP.NET Core规范的方式,直接返回FileStreamResult,同时配置Content-Disposition为inline让浏览器直接打开PDF:

[AllowAnonymous]
[HttpGet("openPDF")]
public async Task<IActionResult> OpenPDF([FromQuery] string url)
{
    using var httpClient = _httpClientFactory.CreateClient();
    var pdfStream = await httpClient.GetStreamAsync(url);
    
    // 配置Content-Disposition为inline,指定文件名可选
    var contentDisposition = new ContentDispositionHeaderValue("inline")
    {
        FileName = "document.pdf"
    };
    Response.Headers.Append("Content-Disposition", contentDisposition.ToString());
    
    return File(pdfStream, "application/pdf");
}

方案2:直接操作Response输出流

如果需要更底层的控制,可以直接向响应流写入PDF内容:

[AllowAnonymous]
[HttpGet("openPDF")]
public async Task OpenPDF([FromQuery] string url)
{
    using var httpClient = _httpClientFactory.CreateClient();
    using var pdfStream = await httpClient.GetStreamAsync(url);
    
    // 设置响应头
    Response.ContentType = "application/pdf";
    Response.Headers.Append("Content-Disposition", "inline; filename=\"document.pdf\"");
    
    // 将PDF流复制到响应流
    await pdfStream.CopyToAsync(Response.Body);
    await Response.Body.FlushAsync();
}

为什么之前的代码无效?

你之前尝试返回HttpResponseMessage的方式,在ASP.NET Core中属于兼容旧Web API的模式,框架会把HttpResponseMessage对象本身序列化成JSON(比如把状态码、头信息、内容等转成JSON结构),而不是把你放入的Stream作为响应体发送给客户端,所以无论怎么设置Content-Type,最终返回的都是JSON格式的HttpResponseMessage对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:03:32