注:BuildManager编译的View结果默认路径为"%WinDir\Microsoft.NET\Framework\ {Version No}\Temporary ASPNET Files"目录下,以App_Web_开头的程序集中,程序集的名称是根据路径随机生成的。
使用示例代码演示View的渲染过程下面就用代码的方式来演示View的查找、编译、激活以及渲染的全过程:
全量代码:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Compilation; 7 using System.Web.Mvc; 8 using System.Web.WebPages; 9 10 namespace My_Blog.Controllers 11 { 12 public class ViewRenderController : Controller 13 { 14 // GET: ViewRender 15 public void Index() 16 { 17 var path = ""; 18 var viewEngineResult = this.FindView(out path);//查找View 19 Render(viewEngineResult, path);//渲染View 20 } 21 22 //View的查找,相当于RazorViewEngine 23 private ViewEngineResult FindView(out string path) 24 { 25 var actionName = "Contact"; 26 var controllerName = "Home"; 27 var viewLocationFormat = @"~/Views/{1}/{0}.cshtml"; 28 //根据Controller和Action名称与地址模板组成View相对路径 29 path = string.Format(viewLocationFormat, actionName, controllerName); 30 //根据文件路径创建RazorView和ViewEngineResult 31 var view = new RazorView(this.ControllerContext, path, "", true, null, null); 32 return new ViewEngineResult(view, new RazorViewEngine()); 33 } 34 35 //View的渲染 36 private void Render(ViewEngineResult viewEngineResult,string path) 37 { 38 Type pageType = BuildManager.GetCompiledType(path);//根据对View文件进行编译 39 var pageInstance = Activator.CreateInstance(pageType);//创建View文件编译后类型实例 40 var webViewPage = this.InitViewPage(pageInstance, viewEngineResult, path);//对实例中相关属性进行初始化 41 webViewPage.ExecutePageHierarchy(//完成View的渲染 42 new WebPageContext(this.HttpContext, null, null), 43 this.HttpContext.Response.Output, null);//startpage设置为null,将不会渲染布局页面 44 } 45 46 private WebViewPage InitViewPage(object instance, ViewEngineResult viewEngineResult, string path) 47 { 48 WebViewPage webViewPage = instance as WebViewPage; 49 50 if (webViewPage == null) 51 { 52 throw new InvalidOperationException("无效"); 53 } 54 ViewContext viewContext = new ViewContext(this.ControllerContext, 55 viewEngineResult.View, 56 this.ViewData, 57 this.TempData, 58 this.HttpContext.Response.Output); 59 webViewPage.VirtualPath = path; 60 61 webViewPage.ViewContext = viewContext; 62 webViewPage.ViewData = viewContext.ViewData; 63 webViewPage.InitHelpers(); 64 return webViewPage; 65 } 66 } 67 }