相关疑难解决方法(0)

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

在常规的MVC控制器中,我们可以用a输出pdf FileContentResult.

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

    return File(stream.GetBuffer(), "application/pdf", "test.pdf");
}
Run Code Online (Sandbox Code Playgroud)

但是我们怎样才能把它变成一个ApiController

[HttpPost]
public IHttpActionResult Test(TestViewModel vm)
{
     //...
     return Ok(pdfOutput);
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试过但它似乎不起作用.

[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);            
}
Run Code Online (Sandbox Code Playgroud)

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

{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]}
Run Code Online (Sandbox Code Playgroud)

在SO上有类似的帖子:从ASP.NET Web API中的控制器返回二进制文件 .它讨论输出现有文件.但我无法使用流.

有什么建议?

c# asp.net asp.net-mvc asp.net-web-api

158
推荐指数
6
解决办法
24万
查看次数

标签 统计

asp.net ×1

asp.net-mvc ×1

asp.net-web-api ×1

c# ×1