5

尽管@Html.RenderPartial调用 write 并返回void,它仍然是写入StringWriter/ StringBuilder。有没有办法直接渲染到ResponseStream?

这可以通过实现像直接输出到的IViewEngine渲染的自定义来完成吗?PdfViewResponseStream

添加

ViewResultBase.ExecuteResult显示ViewContext正在构建Response.Output,但调试器显示ViewContext.WriterStringWriter

这两种方法都会导致StringWriter

return PartialView("view", Model)
// or
PartialView("view", Model).ExecuteResult(ControllerContext)

编辑

似乎System.Web.WebPages.WebPageBase ExecutePageHeirarchy将临时推StringWriter送到上下文堆栈中,所以我不确定是否可以绕过

总之

RenderPartial、RenderAction 不直接输出到 Response.Stream,Razor Views 都不会

解决方案

它是新的 WebPages/Razor 渲染引擎,它用 aStringWriter到 a包装了所有内容StringBuilder。解决方案是更改我的页面以使用 WebFormViewEngine不应用此包装的页面。

4

1 回答 1

0

下面的方法说明了实现您正在寻找的结果的一种方法:

// <summary>
// An extension methods for rendering a model/view into a stream
// </summary>
// <param name="myModel">The model you are trying render to a stream</param>
// <param name="controllerBase">This will come from your executing action</param>
// <returns></returns>
        public static Stream GetStream(CustomModel myModel, ControllerBase controllerBase)
        {
            //we will return this stream
            MemoryStream stream = new MemoryStream();

            //you can add variables to the view data
            controllerBase.ViewData["ViewDataVariable1"] = true;

            //set your model
            controllerBase.ViewData.Model = myModel;

            //The example uses the UTF-8 encoding, you should change that if you are using some other encoding.
            //write to a stream
            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
            {
                using (var sw = new StringWriter())
                {
                    //render the view  ~/Views/Shared/_FeedbackMessage.cshtml (can be passed in as a parameter if you want to make it super generic)
                    var viewResult = ViewEngines.Engines.FindPartialView(controllerBase.ControllerContext, "_FeedbackMessage");

                    //create a new view context
                    var viewContext = new ViewContext(controllerBase.ControllerContext, viewResult.View, controllerBase.ViewData, controllerBase.TempData, sw);

                    //Render the viewengine and let razor do its magic
                    viewResult.View.Render(viewContext, sw);    
                    viewResult.ViewEngine.ReleaseView(controllerBase.ControllerContext, viewResult.View);

                    //get StringBuilder from StringWriter sw and write into the stream writer
                    //you could simply return the StringWriter here if that is what you were interested in doing
                    writer.Write(sw.GetStringBuilder().ToString());

                    writer.Flush();

                    stream.Position = 0;
                }

            }

            //return the stream from the above process
            return stream;
        }
于 2015-12-31T11:04:06.847 回答