【发布时间】:2014-11-20 05:49:33
【问题描述】:
在常规的 MVC 控制器中,我们可以输出带有 FileContentResult 的 pdf。
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 上有一个类似的帖子:Returning binary file from controller in ASP.NET Web API 。它谈论输出现有文件。但我无法让它与流一起使用。
有什么建议吗?
【问题讨论】:
-
这篇文章帮助了我:stackoverflow.com/a/23768883/585552
标签: c# asp.net asp.net-mvc asp.net-web-api