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

.NET Core WebAPI返回JSON而非PDF文件下载问题

解决.NET Core WebAPI返回HttpResponseMessage成JSON而非触发PDF下载的问题

问题原因

在.NET Core WebAPI中,直接返回HttpResponseMessage会被框架当作普通CLR对象序列化输出为JSON,而非作为HTTP文件响应处理。这是因为.NET Core WebAPI的响应模型与旧版ASP.NET Web API不同,它不自动解析HttpResponseMessage来构建响应,而是默认序列化返回的对象。

解决方案

将控制器方法的返回类型改为IActionResult,并使用控制器基类提供的File方法返回文件流,框架会自动处理正确的HTTP头和文件输出。

代码示例(字节数组方式,小文件适用)

public IActionResult DownloadPdf()
{
    var filePath = @"C:\data\test12.pdf";
    var fileBytes = System.IO.File.ReadAllBytes(filePath);
    var fileName = file.Rows[0][1].ToString();

    // 设置Content-Disposition:attachment触发下载,inline浏览器内打开
    var contentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = fileName
    };
    Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

    return File(fileBytes, "application/pdf");
}

代码示例(流方式,大文件友好)

public IActionResult DownloadPdf()
{
    var filePath = @"C:\data\test12.pdf";
    var fileName = file.Rows[0][1].ToString();
    // 使用FileStream避免一次性加载大文件到内存
    var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    var contentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = fileName
    };
    Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

    return File(stream, "application/pdf");
}

关键说明

  • 控制器方法必须返回IActionResult(或其派生类型),这是.NET Core WebAPI的标准响应类型
  • File方法会自动处理HTTP响应的Content-Type、Content-Length等头信息,无需手动构建HttpResponseMessage
  • Content-Disposition的attachment值会触发浏览器弹出下载对话框,inline则会尝试在浏览器窗口内直接打开PDF(取决于浏览器支持)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:45:41