珂珂的个人博客 - 一个程序猿的个人网站

MVC生成静态html页的做法

 这个问题该怎么描述呢,我就是想获取到html再自己处理,貌似可以用HttpModule然后重写Response.Filter的Stream

MVC我的做法是

public static string RenderPartialViewToString(Controller controller, string viewName, object model)
        {
            controller.ViewData.Model = model;
            StringWriter sw = new StringWriter();
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            //ViewResult r = View("~/Views/Blog/Themes/" + article.themeName + "/Show.cshtml", model);
            //ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, r.ViewName, null);
            //HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
            try
            {
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, viewContext.Writer);

                return sw.GetStringBuilder().ToString();
                //sw.ToString
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                sw.Close();
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
            }
        }

返回结果就是生成的html

    下面来做一些处理,每隔一定时间来刷新

 /// <summary>
        /// 创建静态页
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="viewName"></param>
        /// <param name="GetModelMethod">获取模型的方法</param>
        /// <param name="folderPath">静态页保存的路径</param>
        /// <param name="indexName">如果路径为/  使用的文件名 如index.html</param>
        /// <returns></returns>
        public static ActionResult CreateStaticHtml(Controller controller, string viewName, Func<object> GetModelMethod, string folderPath, string indexName)
        {
            folderPath = folderPath.TrimEnd('/');
            //是否启用静态页
            bool isUseStaticHtml = (System.Configuration.ConfigurationManager.AppSettings["isUseStaticHtml"] == "true");
            if (isUseStaticHtml)
            {
                string absPath = controller.Request.Url.AbsolutePath.TrimStart('/');
                if (absPath == "")
                {
                    absPath = indexName;
                }
                //如果目录不存在则创建
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                string s = Directory.GetFiles(folderPath, "*-" + absPath).FirstOrDefault();
                string filePath = String.Empty;
                if (s != null)
                {
                    long updateDate = Convert.ToInt64(Regex.Match(Path.GetFileName(s), "(.*)-" + absPath).Groups[1].Value);
                    filePath = folderPath + "/" + updateDate + "-" + absPath;

                    //默认刷新时间30 分钟
                    int refresh = 1800;
                    string staticHtmlRefreshTimeout = System.Configuration.ConfigurationManager.AppSettings["staticHtmlRefreshTimeout"];
                    if (!String.IsNullOrEmpty(staticHtmlRefreshTimeout))
                    {
                        refresh = Convert.ToInt32(staticHtmlRefreshTimeout);
                    }
                    //如果没有超过刷新时间 则从静态页读取
                    if (Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmss")) - updateDate < refresh)
                    {
                        string content = System.IO.File.ReadAllText(filePath, System.Text.Encoding.UTF8);

                        return new ContentResult { Content = content };
                    }
                }

                filePath = folderPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + absPath;

                //删除以前生成的文件
                if (s != null)
                {
                    System.IO.File.Delete(s);
                }

                object obj = GetModelMethod.Invoke();
                string html = Blogs.Common.ControllerHelper.RenderPartialViewToString(controller, viewName, obj);
                TextWriter w = new StreamWriter(filePath, false, System.Text.Encoding.UTF8, 4096);
                w.Write(html);
                w.Close();

                return new ContentResult { Content = html };
            }

            return null;
        }

每个页的最后更新时间我是加在文件名的前面几个数字,也可以通过读取文件属性。这个方法如果返回Null 则自己再处理

   下面是主页调用

public ActionResult Index()
        {
            string viewName = "~/Views/Blog/Themes/" + base.ThemeName + "/Index.cshtml";
            ActionResult result = Blogs.Common.ControllerHelper.CreateStaticHtml(this, viewName, () =>
            {
                return GetBlogPageModel();
            }, Server.MapPath("~/App_Data/html"), "index.html");

            if (result == null)
            {
                return View(viewName, GetBlogPageModel());
            }
            else
            {
                return result;
            }
        }




上一篇:wordpress3.6 修改的地方

下一篇:个人代码全部开源


0 评论

查看所有评论

给个评论吧