在常规的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的文章:在ASP中从控制器返回二进制文件。NET Web API
。它讨论的是输出一个现有文件。但是我不能让它在溪流中工作。
有什么建议吗?
对我来说,这就是
var response = Request.CreateResponse(HttpStatusCode.OK, new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
and
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
第一个是返回StringContent的JSON表示形式:{"Headers":[{"Key":"Content-Type","Value":["application/octet-stream;charset = utf - 8”]}]}
而第二个则是正常返回文件。
似乎请求。CreateResponse有一个重载,它将字符串作为第二个参数,这似乎是导致StringContent对象本身呈现为字符串而不是实际内容的原因。
对我来说,这就是
var response = Request.CreateResponse(HttpStatusCode.OK, new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
and
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");
第一个是返回StringContent的JSON表示形式:{"Headers":[{"Key":"Content-Type","Value":["application/octet-stream;charset = utf - 8”]}]}
而第二个则是正常返回文件。
似乎请求。CreateResponse有一个重载,它将字符串作为第二个参数,这似乎是导致StringContent对象本身呈现为字符串而不是实际内容的原因。