.NET Core pdf下载程序“未找到内容类型'application / pdf'的输出格式化程序...”

问题描述

我正在创建.NET Core 3.1 Web API方法,以下载给定文件名的pdf。该方法在使用NSwag生成其客户代码的团队之间共享。

我最近将生产属性Produces("Application/pdf")更改为json,此更改是必需的,以便其他团队可以生成有效的客户代码。但是,自从进行此更改以来,我无法从该方法下载任何文件。下载文档的请求返回406错误(在Postman中),并且以下错误记录到服务器事件查看器中。

No output formatter was found for content types 'application/pdf,application/pdf' to write the response.

将产生的内容类型恢复为'application / json'确实允许下载文档,但是如上所述,该值必须为pdf。

任何建议将不胜感激。

方法


[HttpGet("{*filePath}")]
[ProducesResponseType(typeof(FileStreamResult),StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[Produces("Application/pdf")]
public async Task<ActionResult> GetDocument(string fileName) {

    RolesrequiredHttpContextExtensions.ValidateAppRole(HttpContext,_requiredScopes);

    var memoryStream = new MemoryStream();

    var memoryStream = new MemoryStream();

    using (var stream = new FileStream(filePath,FileMode.Open,FileAccess.Read,FileShare.Read,bufferSize: 4096,useAsync: true)) {
        stream.copyTo(memoryStream);
    }
    memoryStream.Seek(offset: 0,SeekOrigin.Begin);

    return new FileStreamResult(memoryStream,"Application/pdf");
}

解决方法

我正在使用

public asnyc Task<IActionResult> BuildPDF()
{
    Stream pdfStream = _pdfService.GetData();
    byte[] memoryContent = pdfStream.ToArray();

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

,并且有效。你能尝试一下吗?

,

该问题是由于重命名方法参数并且未将[HttpGet(“ {* filePath}”)]更新为[HttpGet(“ {* fileName}”)]]

引起的。 ,

我刚刚遇到了同样的错误,经过一番调查,我发现异常的原因确实在 model binding error 中。您已经在回答中对此进行了说明,但仔细检查后,很明显原因与绑定本身无关,而是与响应正文有关。

由于您指定了 [Produces("application/pdf")],框架假定此内容类型是此操作的唯一可能,但是当抛出异常时,您会得到包含错误描述的 application/json

因此,为了使这项工作同时适用于“快乐路径”和异常,您可以指定多种响应类型:

[Produces("application/pdf","application/json")]
public async Task<ActionResult> GetDocument(string fileName) 
{
...
}