.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等头信息,无需手动构建HttpResponseMessageContent-Disposition的attachment值会触发浏览器弹出下载对话框,inline则会尝试在浏览器窗口内直接打开PDF(取决于浏览器支持)
内容的提问来源于stack exchange,提问作者Naveen
相关产品推荐
相关产品推荐

