标签:content new value this url contex throw 页面 void
页面缓存存放在了Dictionary中,可以自己替换
助手类:
public class StaticHelper { /// <summary> /// 将页面渲染成html字符串 /// </summary> /// <param name="context">传入this.ControllerContext</param> /// <param name="viewPath">静态页面的模板路径</param> /// <param name="model">往模板中传入实体,进行赋值</param> /// <returns></returns> public static string RenderViewToString(ControllerContext context, string viewPath, object model = null) { ViewEngineResult viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null); if (viewEngineResult == null) { throw new FileNotFoundException("View" + viewPath + "cannot be found."); } var view = viewEngineResult.View; context.Controller.ViewData.Model = model; using (var sw = new StringWriter()) { var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw); view.Render(ctx, sw); return sw.ToString(); } } }
ActionFilter:
public class StaticFilterAttribute : ActionFilterAttribute//, IResultFilter { static Dictionary<string, string> DICT = new Dictionary<string, string>(); public override void OnActionExecuting(ActionExecutingContext filterContext) { var url = filterContext.HttpContext.Request.RawUrl; var key = url.GetHashCode().ToString(); if (DICT.TryGetValue(key, out string html)) { var content = new ContentResult(); content.Content = html; filterContext.Result = content; } base.OnActionExecuting(filterContext); } public override void OnActionExecuted(ActionExecutedContext filterContext) { var url = filterContext.HttpContext.Request.RawUrl; var key = url.GetHashCode().ToString(); Person p = new Person { ID = 1, Name = "haha", Birthday=DateTime.Now }; var html = StaticHelper.RenderViewToString(filterContext.Controller.ControllerContext, "~/Views/StaticPage/Index.cshtml", p); DICT.Add(key, html); base.OnActionExecuted(filterContext); } }
未完待续...
标签:content new value this url contex throw 页面 void
原文地址:https://www.cnblogs.com/fanfan-90/p/12155655.html