public static string Render <TModel>(this WebViewPage <TModel> view, HttpContextBase httpContext, TModel model = default(TModel)) { var writer = new StringWriter(); view.ViewData.Model = model; view.Initialize(httpContext, writer); var webPageContext = new WebPageContext(view.ViewContext.HttpContext, page: null, model: null); // Using private reflection to access some internals // Note: ideally we would not have to do this, but WebPages is just not mockable enough :( var dynamicPageContext = webPageContext.AsDynamic(); dynamicPageContext.OutputStack.Push(writer); // Push some section writer dictionary onto the stack. We need two, because the logic in WebPageBase.RenderBody // checks that as a way to make sure the layout page is not called directly var sectionWriters = new Dictionary <string, SectionWriter>(StringComparer.OrdinalIgnoreCase); dynamicPageContext.SectionWritersStack.Push(sectionWriters); dynamicPageContext.SectionWritersStack.Push(sectionWriters); // Set the body delegate to do nothing dynamicPageContext.BodyAction = (Action <TextWriter>)(w => { }); view.AsDynamic().PageContext = webPageContext; view.Execute(); return(writer.ToString()); }