码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-01-06 12:35:38      阅读:115      评论:0      收藏:0      [点我收藏+]

标签: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);
        }
    }

 

 

 

 

未完待续...

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

标签:content   new   value   this   url   contex   throw   页面   void   

原文地址:https://www.cnblogs.com/fanfan-90/p/12155655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!