如何在ASP.NET WebAPI中返回一个文件(FileContentResult)

23 浏览
0 Comments

如何在ASP.NET WebAPI中返回一个文件(FileContentResult)

在一个普通的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。它讨论了如何输出一个已有的文件。但是我无法用流来实现它。

有任何建议吗?

admin 更改状态以发布 2023年5月21日
0
0 Comments

如果您想返回 IHttpActionResult,您可以像这样做:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    var response = ResponseMessage(result);
    return response;
}

0
0 Comments

不必返回StreamContent作为Content,我可以使用ByteArrayContent进行操作。

[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;
}

0