c# - 如何让 OWIN 自托管 MVC 直接写入输出流

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

我在 OWIN 自托管应用程序下使用 MVC 操作,该操作将大量字节作为文件提供给客户端。数据在内存中生成并缓存,MVC 操作返回一个 StreamContent,其中一个 MemoryStream 指向我缓存的 byte[]

我希望数据会直接从我的缓存中读取并复制到 OutputStream。而是将数据从我的 MemoryStream 复制到由基础设施创建的另一个数据流。当并行发出大量请求时,我可以看到进程内存增长:

return new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StreamContent(new MemoryStream(content), content.Length)
    {
        Headers =
        {
            ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileNameStar = fileName,
                Size = content.Length,
            },
            ContentType = MediaTypeHeaderValue.Parse(mediaType),
            ContentLength = content.Length,
        }
    }
};

如何确保直接返回缓存的 MemoryStream 而不会被复制占用更多内存?

最佳答案

为了克服这个问题,您可以通过使用 Request.GetOwinEnvironment() 从 OWIN 环境中获取它来直接写入 OutputStream。要获取写入的响应内容,您可以使用 PushStreamContent 并写入 OutputStream,并在构建响应时调用异步回调。

    var outputStream = ((HttpListenerContext)Request.GetOwinEnvironment()["System.Net.HttpListenerContext"]).Response.OutputStream;
    return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new PushStreamContent(
            async (stream, httpContent, arg3) =>
            {
                await outputStream.WriteAsync(content, 0, content.Length);
                stream.Close();
            })
        {
            Headers =
            {
                ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileNameStar = fileName,
                    Size = content.Length,
                },
                ContentType = MediaTypeHeaderValue.Parse(mediaType),
                ContentLength = content.Length,
            }
        }
    };

关于c# - 如何让 OWIN 自托管 MVC 直接写入输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38171782/

相关文章:

c# - 如何在Windows服务中设置一天的定时器间隔

c# - 组合与继承。我哪里做错了?

asp.net - ClaimsAuthenticationManager 与 IAuthenticationFilter 与 OWIN 表单例份验证

c# - 将多个文本框和标签放在同一列CSS上?

c# - LINQ - 查找一个列表中不在另一个列表中的所有项目

c# - TDD——你测试了多少?

c# - Azure Service Fabric 参与者 - 未处理的异常?

c# - 使用 Xunit 测试多个派生类型的最佳方法是什么?

asp.net - 迁移到 Azure 托管以及如何选择 session 状态、数据库和服务器

c# - control.Show 和 BringToFront 有什么区别?