当前位置:首页 > Web开发 > 正文

string (); public override void OnActionExecuting(ActionExe

2024-03-31 Web开发

页面缓存存放在了Dictionary中,可以本身替换

助手类:

public class StaticHelper { /// <summary> /// 将页面衬着成html字符串 /// </summary> /// <param>传入this.ControllerContext</param> /// <param>静态页面的模板路径</param> /// <param>往模板中传入实体,进行赋值</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); } }

未完待续...

MVC-实现页面缓存or静态化

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32182.html