ASP.NET MVC生成静态页面的方法

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ASP.NET MVC生成静态页面的方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文主要讲述了在asp.NET mvc中,页面静态化的方法。对于网站来说,生成纯htML静态页面除了有利于seo外,还可以减轻网站的负载能力和提高网站性能。

1.先付上封装好生成静态页的原代码:

public class Common
{
  #region 获取模板页的Html代码
  /// <summary>
  /// 获取页面的Html代码
  /// </summary>
  /// <param name="url">模板页面路径</param>
  /// <param name="encoding">页面编码</param>
  /// <returns></returns>
  public static string GetHtml(string url, @R_406_2663@tem.Text.Encoding encoding)
  {
    byte[] buf = new WebClient().DownloadData(url);
    if (encoding != null)
    {
      return encoding.GetString(buf);
    }
    string html = System.Text.Encoding.UTF8.GetString(buf);
    encoding = GetEncoding(html);
    if (encoding == null || encoding == System.Text.Encoding.UTF8)
    {
      return html;
    }
    return encoding.GetString(buf);
  }

  /// <summary>
  /// 获取页面的编码
  /// </summary>
  /// <param name="html">Html码</param>
  /// <returns></returns>
  public static System.Text.Encoding GetEncoding(string html)
  {
    string pattern = @"(?i)\bcharset=(?<charset>[-a-zA-Z_0-9]+)";
    string charset = Regex.Match(html, pattern).Groups["charset"].Value;
    try
    {
      return System.Text.Encoding.GetEncoding(charset);
    }
    catch (argumentException)
    {
      return null;
    }
  }
  #endregion

  #region 用于生成HTML静态页
  /// <summary>
  /// 创建静态文件
  /// </summary>
  /// <param name="result">Html代码</param>
  /// <param name="createpath">生成路径</param>
  /// <returns></returns>
  public static bool CreateFileHtmlByTemp(string result, string createpath)
  {
    if (!string.IsNullOrEmpty(result))
    {
      if (string.IsNullOrEmpty(createpath))
      {
        createpath = "/default.html";
      }
      string filepath = createpath.Substring(createpath.LastIndexOf(@"\"));
      createpath = createpath.Substring(0, createpath.LastIndexOf(@"\"));
      if (!Directory.Exists(createpath))
      {
        Directory.CreateDirectory(createpath);
      }
      createpath = createpath + filepath;

      try
      {
        FileStream fs2 = new FileStream(createpath, FileMode.Create);
        StreamWrITer sw = new StreamWriter(fs2, new System.Text.UTF8Encoding(false));//去除UTF-8 BOM
        sw.Write(result);
        sw.Close();
        fs2.Close();
        fs2.Dispose();
        return true;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
    return false;
  }
  #endregion

  #region 调用静态模板,并且传递数据模型实体类 创建Html静态页
  /// <summary>
  /// 解析模板生成静态页
  /// </summary>
  /// <param name="temppath">模板地址</param>
  /// <param name="path">静态页地址</param>
  /// <param name="t">数据模型</param>
  /// <returns></returns>
  public static bool CreatestaticPage<T>(string temppath, string path, T t)
  {
    try
    {
      //获取模板Html
      string TemplateContent = GetHtml(temppath, System.Text.Encoding.UTF8);

      //初始化结果
      string result = string.Empty;

      //解析模板生成静态页Html代码
      result = Razor.Parse(TemplateContent, t);

      //创建静态文件
      return CreateFileHtmlByTemp(result, path);
    }
    catch (Exception e)
    {
      throw e;
    }
  }
  #endregion
}

2.调用方法(创建一个多线程去执行,效果会更好):

//实例化调用方法
Task tk = new Task(CreateStaticHtml);
tk.Start();
//静态调用方法
Task.Factory.StartNew(() => CreateStatichtml());

3.封装好的静态方法:

/// <summary>
/// 创建静态页面
/// </summary>
public void CreateStaticHtml()
{
  using (BangLiEntities bangLi = new BangLiEntities())
  {
    View_Home view_Home = new View_Home();
    view_Home.COMmandAdExtendList = Dal.CommandAdDal.Instance(bangLi).GetInit().ToList();
    view_Home.NewsList = bangLi.News.OrderByDescending(u => u.AddDateTime).Take(5).ToList();
    view_Home.NewsExtendList = Dal.NewsDal.Instance(bangLi).GetInit().OrderByDescending(u => u.AddDateTime).Take(5).ToList();
    view_Home.News = Dal.NewsDal.Instance(bangLi).GetInit().Where(u => u.Id == 3).SingleOrDefault();
    string TemplateContent = Common.GetHtml(Server.MapPath("/Views/SourceHtml/Home/Index.cshtml"), System.Text.Encoding.UTF8);
    //初始化结果
    string result = string.Empty;
    //解析模板生成静态页Html代码
    result = Razor.Parse(TemplateContent, view_Home);
    //创建静态文件
    Common.CreateFileHtmlByTemp(result, Server.MapPath("/Resource/Manage/Html/Home/Index.html"));
  }
}

4.如首页执行时,可以在执行Action前去执行一个过滤器:

public class MyFirstHomeAttribute:ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    VAR context = filterContext.HttpContext;
    context.Session["IsStaticHtml"] = false;
    string path = context.Server.MapPath("/Resource/Manage/Html/Home/Index.html");
    if (System.IO.File.Exists(path))
    {
      string html = System.IO.File.ReadAllText(path);
      context.Response.Write(html);
      context.Session["IsStaticHtml"] = true;
      context.Response.End();
    }
  }
}

5.执行首页:

[MyFirstHome]
public ActionResult Index()
{
  View_Home view_Home = null;
  var IsStaticHtml = Convert.ToBoolean(Session["IsStaticHtml"]);
  if (!IsStaticHtml)
  {
    view_Home = new View_Home();
    using (BangLiEntities bangLi = new BangLiEntities())
    {
      view_Home.CommandAdExtendList = Dal.CommandAdDal.Instance(bangLi).GetInit().ToList();
      view_Home.NewsExtendList = Dal.NewsDal.Instance(bangLi).GetInit().OrderByDescending(u => u.AddDateTime).Take(5).ToList();
          
    }
    return View(view_Home);
  }
  else
  {
    return null;
  }
}

说明:可以让一个超链接或跳转地址直接跳转到一个html的静态页面,速度会更快;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的ASP.NET MVC生成静态页面的方法全部内容,希望文章能够帮你解决ASP.NET MVC生成静态页面的方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。