当前位置:Gxlcms > asp.net > ASP.NET MVC生成静态页面的方法

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

时间:2021-07-01 10:21:17 帮助过:13人阅读

本文主要讲述了在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, System.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的静态页面,速度会更快;

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

人气教程排行