mvc动态网页 静态化

在  Commen命名空间下 PageCovert类中的静态方法

 public static bool WriteFile(Article article, string naviget)
        {
            string path = HttpContext.Current.Server.MapPath("/news/ ");//定义html文件存放路径
            Encoding code = Encoding.GetEncoding("utf-8");//定义文字编码 这里要看静态模版的编码
            // 读取模板文件
            string tempPath = HttpContext.Current.Server.MapPath("/news/Templete.html");
            StreamReader sr = null;
            StreamWriter sw = null;
            string str = " ";
            try
            {
                sr = new StreamReader(tempPath, code);
                str = sr.ReadToEnd(); // 读取文件
            }
            catch (Exception exp)
            {
                HttpContext.Current.Response.Write(exp.Message);
                HttpContext.Current.Response.End();
            }
            finally
            {
                sr.Close();
            }
            string htmlFile = path + article.ID + ".html ";//aId.html 静态页面的名字
            // 替换内容
            str = str.Replace("$PlateNavigationHtml$", naviget);
            str = str.Replace("$Title$", article.Title);
            str = str.Replace("$SubTitle$", article.SubTitle);
            str = str.Replace("$Author$", article.AuthorName);
            str = str.Replace("$PublishDate$", article.PublishDate.ToString("yyyy-MM-dd hh"));
            str = str.Replace("$From$", article.ArticleFrom);
            str = str.Replace("$Des$", article.Des);
            str = str.Replace("$Context$", article.Context).Replace("/Upload/images","../Upload/images");

            // 写文件
            try
            {
                sw = new StreamWriter(htmlFile, false, code);
                sw.Write(str);
                sw.Flush();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
                HttpContext.Current.Response.End();
            }
            finally
            {
                sw.Close();
            }
            return true;
        }
    }

方法的调用

 string naviget = "<a href=''/>栏目</a>";//页眉导航
                Commen.PageConvert.WriteFile(addArticle, naviget);

原文地址:https://www.cnblogs.com/nanxiaoxiang/p/2662217.html