在常規的MVC控制器中,我們可以使用FileContentResult
輸出pdf。如何在ASP.NET WebAPI中返回文件(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:Returning binary file from controller in ASP.NET Web API 。它討論輸出一個現有的文件。但是我無法讓它在一個流中工作。
有什麼建議嗎?
這篇文章幫助了我:http://stackoverflow.com/a/23768883/585552 – Greg 2015-09-23 00:48:29