如何从 MVC 视图返回流?
我相信我已经相当接近了,但我的流要么为空,要么已被处置。这是示例代码。
var ms = new MemoryStream();
using (var sw = new StreamWriter(ms))
{
using (var tw = new HtmlTextWriter(sw))
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, tw);
ms.Position = 0;
return ms;
}
}
调用代码会导致 objectDisposeException,因为流已被释放。如果我将 return 移到 using 之外,则结果为 null。我在这里做错了什么?我有什么想法可以让它正常工作吗?
I'm fairly close I believe but my stream is either null or its been disposed. Here is the sample code.
var ms = new MemoryStream();
using (var sw = new StreamWriter(ms))
{
using (var tw = new HtmlTextWriter(sw))
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, tw);
ms.Position = 0;
return ms;
}
}
the calling code results in an objectDisposedException because the stream is disposed. If I move the return outside of the using, the result is null. What am I doing wrong here? Any ideas how I can this to work correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
StreamWriter
上的 using 语句也将关闭底层流。删除
StreamWriter
上的using
语句以保持流处于活动状态。另一种选择是返回字节数组而不是内存流。
The using statement on the
StreamWriter
will also close the underlying stream.Remove the
using
statement on theStreamWriter
to keep the stream alive.Another option would be to return a byte array rather than a memory stream.
要在
using
块中使用某个类,该类必须实现IDisposable
。当块结束时,它会调用 IDisposable.Dispose() 来处置您的 Stream。这是一个很好的做法,但如果您想要流,请删除using
或将 return 放入其中。我会选择第二个选择。To use a class in a
using
block, that class must implementIDisposable
. When the block ends, it invokesIDisposable.Dispose()
which disposes your Stream. This is a good practice, but if you want the stream, either remove theusing
or put the return inside it. I would go with the second option.你有 2 个 using,他说将 return 放在外部 using() 中,
如下所示
You have 2 usings he is saying put the return inside of the outter using()
like this