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

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

在常规 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/

相关文章:

c# - 使用Partial Classes来管理代码,好的解决方案?

c# - 检查泛型类型是否继承自泛型接口(interface)

c# - 如何在没有root的情况下获取绝对url?

c# - 在 data-originalvalue 属性中使用时,MVC 4 View Page 中的 Null Reference Exception?

c# - 使用 web.config 时,配置类不可用

asp.net-mvc - 防止用户在asp.net模型验证的表单输入过程中输入空格吗?

c# - 使用 SIMD (System.Numerics) 编写向量求和函数并使其比 for 循环更快

javascript - 页面加载后来自控件的空引用

ASP.NET 通用提供程序

asp.net - 将小整数值哈希为大的 16 位唯一数字