使用Asp.net Core 1.1中的nodeservices下载生成的pdf的byte []

Ana*_*dad 7 c# pdf download asp.net-core asp.net-core-1.1

我正在尝试下载nodeServices生成的pdf文件,该文件采用字节数组的形式.这是我的原始代码:

[HttpGet]
[Route("[action]/{appId}")]
public async Task<IActionResult> Pdf(Guid appId, [FromServices] INodeServices nodeServices)
{
    // generateHtml(appId) is a function where my model is converted to html.
    // then nodeservices will generate the pdf for me as byte[].
    var result = await nodeServices.InvokeAsync<byte[]>("./pdf", 
            await generateHtml(appId));
    HttpContext.Response.ContentType = "application/pdf";
    HttpContext.Response.Headers.Add("x-filename", "myFile.pdf");
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
    HttpContext.Response.Body.Write(result, 0, result.Length);
    return new ContentResult();
}
Run Code Online (Sandbox Code Playgroud)

此代码工作正常,它将在浏览器中显示pdf文件,例如.chrome,当我尝试下载它时,我得到"失败,网络错误".

我在这里和那里搜索过,我看到了一些返回文件的建议:

return File(result, "application/pdf");
Run Code Online (Sandbox Code Playgroud)

这也不起作用,另一件事是添加"Content-Disposition"标题:

HttpContext.Response.Headers.Add("Content-Disposition", string.Format("inline;filename={0}", "myFile.pdf"));
Run Code Online (Sandbox Code Playgroud)

其他人建议使用FileStreamResult,也没有好处.我意识到问题可能是关于我生成的文件(byte [])没有自己的路径或链接,所以我将字节保存到我的服务器,然后通过其路径再次获取文件,然后到内存流,最后返回一个包含内存流的文件:

var result = await nodeServices.InvokeAsync<byte[]>("./pdf", await generateHtml(appId));
var tempfilepath = Path.Combine(_environment.WebRootPath, $"temp/{appId}.pdf");

System.IO.File.WriteAllBytes(tempfilepath, result);

var memory = new MemoryStream();
using (var stream = new FileStream(tempfilepath, FileMode.Open))
{
    await stream.CopyToAsync(memory);
}
memory.Position = 0;

return File(memory, "application/pdf", Path.GetFileName(tempfilepath));
Run Code Online (Sandbox Code Playgroud)

哪个有效!它在浏览器中显示了该文件,我可以下载它,但是,我不希望任何文件存储在我的服务器上,我的问题是,我不能只是下载文件而不需要存储它吗?

Ste*_*t_R 9

您仍然可以在FileContentResult不将字节数组转换为流的情况下返回.File()方法有一个重载,它采用fileContents字节数组和contentType字符串.

所以你可以重构像:

public async Task<IActionResult> Pdf(Guid appId, [FromServices] INodeServices nodeServices)
{
    var result = await nodeServices.InvokeAsync<byte[]>("./pdf", 
            await generateHtml(appId));

    return File(result, "application/pdf","myFile.pdf");
}
Run Code Online (Sandbox Code Playgroud)