在 MVC 项目中,我使用以下代码将视图动态呈现为字符串。
public string RenderViewToString(string viewName, object model, RequestContext requestContext){
ViewData.Model = model;
var cContext = ControllerContext;
if (cContext == null)
{
var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
var ctrl = ctrlFactory.CreateController(requestContext, "Documents") as Controller;
var newCContext = new ControllerContext(requestContext, ctrl);
cContext = newCContext;
var ctrlDesc = new ReflectedControllerDescriptor(ctrl.GetType());
}
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(cContext, viewName);
var viewContext = new ViewContext(cContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(cContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
这工作正常,直到多个用户同时运行代码。然后它将每个用户的视图数据混合在一起。
任何建议为什么?谢谢