在常规 MVC Controller 中,我们可以使用 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 .它谈论输出现有文件。但我无法让它与流一起工作。
有什么建议吗?
最佳答案
我可以让它与 ByteArrayContent
一起使用,而不是将 StreamContent
作为 Content
返回。
[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;
}
关于c# - 如何在 ASP.NET WebAPI 中返回文件 (FileContentResult),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50894507/