小编典典

如何在ASP.NET WebAPI中返回文件(FileContentResult)

c#

在常规MVC控制器中,我们可以使用来输出pdf FileContentResult

public FileContentResult Test(TestViewModel vm)
{
    var stream = new MemoryStream();
    //... add content to the stream.

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

但是如何将其更改为ApiController

[HttpPost]
public IHttpActionResult Test(TestViewModel vm)
{
     //...
     return Ok(pdfOutput);
}

这是我尝试过的方法,但似乎不起作用。

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();
    //...
    var content = new StreamContent(stream);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    content.Headers.ContentLength = stream.GetBuffer().Length;
    return Ok(content);            
}

在浏览器中显示的返回结果是:

{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]}

SO上也有类似的文章:从ASP.NET Web API中的控制器返回二进制文件
。它讨论输出现有文件。但是我无法使其与流一起工作。

有什么建议么?


阅读 1808

收藏
2020-05-19

共1个答案

小编典典

我可以使它与一起使用,而不是返回StreamContentas 。Content``ByteArrayContent

[HttpGet]
public HttpResponseMessage Generate()
{
    var stream = new MemoryStream();
    // processing the stream.

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.ToArray())
    };
    result.Content.Headers.ContentDisposition =
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CertificationCard.pdf"
    };
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");

    return result;
}
2020-05-19