HttpContext.Response.OutputStream 在 WebAPI 的 HttpResponseMessage 中使用的替代方法是什么

Noa*_*nil 1 asp.net-web-api httpresponsemessage

我正在编写一个用于处理 PDF 文档的 WebAPI。它是在之前实现 IHttpHandler 并使用 HttpContext 获取上下文的 ashx 页面中编写的。我现在正在使用 WebAPI 编写它。在 WebAPI 中,我们有 HttpResponseMessage。对于 HttpContext.Response.BinaryWrite,我们在 HttpResponseMessage 中有新的 ByteArrayContent。但是 WebAPI 中 HttpContext.Response.OutputStream 的替代方案是什么?我需要在 WebAPI 中使用 OutputStram 的替代方案,因为我将此 OutputStream 作为参数传递给另一个 dll。

ashx 中的代码:

SomeReport.PdfReport rpt = new SomeReport.PdfReport(docID);
rpt.CreateReport(context.Response.OutputStream);
Run Code Online (Sandbox Code Playgroud)

Iva*_* R. 6

实际上,例如您可以使用任何流,MemoryStream但结果应包装到StreamContent.

public HttpResponseMessage Get()
{
    var response = Request.CreateResponse();

    var outputStream = new MemoryStream();

    //write data to output stream
    //or passing it to somewhere
    outputStream.WriteByte(83);

    outputStream.Position = 0;
    response.Content = new StreamContent(outputStream);

    return response;    
}
Run Code Online (Sandbox Code Playgroud)

如果您需要直接写入输出流,请考虑使用PushStreamContent. 例子