IProcessHostPreloadClient
我最近开始玩弄 IIS 通过使用界面将预热步骤应用到我的 Web 应用程序的能力(在此处查找有关如何设置的指导)。这效果很好,或者至少我认为它确实如此,因为我做的一件“聪明”的事情是尝试通过迭代我的控制器并渲染它们来预加载我的视图。
经过一番反复试验,我让它工作了,一切都很好。也就是说,直到我注意到我的系统的所有验证都不再有效,无论是客户端验证还是服务器验证。我假设当 MVC 第一次检索视图时验证通常与视图相关联,但我没有这样做。有谁知道如何将其包含在我的解决方案中或以其他方式完成?
编码:
public class Warmup : IProcessHostPreloadClient
{
public void Preload(string[] parameters)
{
//Pre-render all views
AutoPrimeViewCache("QASW.Web.Mvc.Controllers", @"Views\");
AutoPrimeViewCache("QASW.Web.Mvc.Areas.Api.Controllers", @"Areas\Api\Views\", "Api");
}
private void AutoPrimeViewCache(string controllerNamespace, string relativeViewPath, string area = null)
{
var controllerTypes = typeof(Warmup).Assembly.GetTypes().Where(t => t.Namespace == controllerNamespace && (t == typeof(Controller) || t.IsSubclassOf(typeof(Controller))));
var controllers = controllerTypes.Select(t => new { Instance = (Controller)Activator.CreateInstance(t), Name = t.Name.Remove("Controller") });
foreach (var controller in controllers)
{
var viewPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, relativeViewPath + controller.Name);
var viewDir = new DirectoryInfo(viewPath);
if (viewDir.Exists)
{
var viewNames = viewDir.EnumerateFiles("*.cshtml").Select(f => f.Name.Remove(".cshtml")).ToArray();
PreloadController(controller.Instance, area, viewNames);
}
}
}
private void PreloadController(Controller controller, string area, params string[] views)
{
var viewEngine = new RazorViewEngine();
var controllerName = controller.GetType().Name.Remove("Controller");
var http = new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://a.b.com", null), new HttpResponse(TextWriter.Null)));
var routeDescription = area == null ? "{controller}/{action}/{id}" : area + "/{controller}/{action}/{id}";
var route = new RouteCollection().MapRoute(
"Default", // Route name
routeDescription, // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
var routeData = new RouteData(route, route.RouteHandler);
routeData.Values.Add("controller", controllerName);
if (area != null)
{
routeData.Values.Add("area", area);
routeData.DataTokens.Add("area", area);
}
routeData.DataTokens.Add("controller", controllerName);
routeData.Values.Add("id", 1);
routeData.DataTokens.Add("id", 1);
var controllerContext = new ControllerContext(http, routeData, controller);
var vDic = new ViewDataDictionary();
var vTemp = new TempDataDictionary();
foreach (var view in views)
{
var viewResult = viewEngine.FindView(controllerContext, view, null, false);
if (viewResult.View == null)
throw new ArgumentException("View not found: {0} (Controller: {1})".Args(view, controllerName));
var viewContext = new ViewContext(controllerContext, viewResult.View, vDic, vTemp, TextWriter.Null);
try { viewResult.View.Render(viewContext, TextWriter.Null); }
catch { }
}
}
}