首页 > 解决方案 > UseStaticFiles OnPrepareResponse 在运行时切换流

问题描述

是否可以用另一个图像流替换原始图像流?

看来我无法将 sr 分配给 HttpResponse

使用 asp 核心 2

有可能做到这一点还是有其他方法可以做到这一点?

 app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = x =>
                {   
                    if (x.Context.Request.Path.Value.StartsWith("/images/"))
                    {
                        using (var sr = File.OpenRead(path))
                        {             
/// Here I need to replace the original stream with the stream from the sr.
                            x.Context.Response.Body = sr;
                        }
                    }
                }
            });

标签: c#asp.net-core

解决方案


这有效...

        app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = x =>
            {   
                if (x.Context.Request.Path.Value.StartsWith("/images/"))
                {
                    using (var sr = File.OpenRead(path))
                    {             
                        HttpResponse hr = x.Context.Response;
                        hr.ContentLength = sr.Length;
                        sr.CopyTo(x.Context.Response.Body);
                    }
                }
            }
        });       

推荐阅读