C#控制器能否设置Blob响应类型?Swagger生成客户端PDF预览报错
解决方案:C#控制器返回Blob实现PDF预览并解决解析错误
一、C#控制器正确配置
完全可以在C#控制器中返回Blob类型的PDF响应,核心是通过File方法返回二进制内容,同时修正Swagger注解:
[HttpGet("preview-pdf")] // 指定响应内容类型为PDF [Produces("application/pdf")] // 告知Swagger响应返回二进制字节数组 [ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)] public IActionResult GetPdfPreview() { // 替换为你的PDF生成/获取逻辑(比如从数据库读取、动态生成字节数组) byte[] pdfContent = GetYourPdfData(); // 返回文件流,第三个参数为可选下载文件名 return File(pdfContent, "application/pdf", "document-preview.pdf"); }
如果通过Stream返回PDF:
[HttpGet("preview-pdf")] [Produces("application/pdf")] [ProducesResponseType(typeof(Stream), StatusCodes.Status200OK)] public IActionResult GetPdfPreview() { using var pdfStream = new FileStream("path/to/your/pdf/file.pdf", FileMode.Open, FileAccess.Read); return File(pdfStream, "application/pdf"); }
二、Angular客户端修正(核心解决解析错误)
你遇到的"http failure during parsing"错误,是因为Angular默认将响应按JSON解析,而服务器返回的是二进制PDF。必须在请求时指定responseType: 'blob',同时修正Blob创建的语法错误:
import { HttpClient } from '@angular/common/http'; // 在组件或服务中发起请求 constructor(private http: HttpClient) {} openPdfPreview() { this.http.get('/api/preview-pdf', { responseType: 'blob' }).subscribe( (response: Blob) => { const blob = new Blob([response], { type: 'application/pdf' }); const previewUrl = URL.createObjectURL(blob); window.open(previewUrl); }, (error) => { console.error('PDF预览失败:', error); } ); }
三、错误原因说明
本地运行正常可能是因为本地环境的响应处理逻辑较宽松,但服务器端的响应头或内容格式触发了Angular的默认JSON解析逻辑,导致解析失败。指定responseType: 'blob'后,Angular会直接将响应作为二进制Blob处理,不再尝试解析为JSON,即可解决该问题。
内容的提问来源于stack exchange,提问作者VMG
相关产品推荐
相关产品推荐

