对的,这是可能的。
我确信您现在知道 Razor 视图引擎会在写入响应流之前写入临时缓冲区,这就是为什么当您调用另一个操作时,标记会乱序写入响应。
我过去使用的解决方法是将任何写入临时重定向到响应,MemoryStream
而您正在尝试呈现另一个操作,然后MvcHtmlString
从MemoryStream
.
所以像:
public class HttpResonseCapture : IDisposable
{
private readonly MemoryStream _stream = new MemoryStream();
private readonly Stream _originalStream;
private readonly HttpContextBase _httpContext;
public HttpResponseCapture(HttpContextBase httpContext)
{
_httpContext = httpContext;
_originalStream = httpContext.Response.OutputStream;
httpContext.Response.OutputStream = _stream;
}
public MvcHtmlString ToHtmlString()
{
return MvcHtmlString.Create(Encoding.Unicode.GetString(_stream.ToArray()));
}
public void Dispose()
{
_httpContext.Response.OutputStream = _originalStream;
_stream.Dispose();
}
}
可以这样使用:
using (var responseCapture = new HttpResponseCapture(httpContext))
{
// Call other action here
var result = responseCapture.ToHtmlString();
}