ASP. NET MVC Method for Generating Static Pages

  • 2021-09-12 00:51:31
  • OfStack

This article mainly describes the static method of page in asp. NET mvc. For websites, generating pure html static pages can not only benefit seo, but also reduce the load capacity of websites and improve the performance of websites.

1. Pay the original code that encapsulates the static page first:


public class Common
{
  #region  Object of the template page Html Code 
  /// <summary>
  ///  Object of the page Html Code 
  /// </summary>
  /// <param name="url"> Template page path </param>
  /// <param name="encoding"> Page coding </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>
  ///  Get the encoding of the page 
  /// </summary>
  /// <param name="html">Html Source code </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  Used to generate Html Static page 
  /// <summary>
  ///  Create a static file 
  /// </summary>
  /// <param name="result">Html Code </param>
  /// <param name="createpath"> Generation path </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));// Removal UTF-8 BOM
        sw.Write(result);
        sw.Close();
        fs2.Close();
        fs2.Dispose();
        return true;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
    return false;
  }
  #endregion

  #region  Invoke static templates and pass data model entity classes   Create Html Static page 
  /// <summary>
  ///  Parsing Templates to Generate Static Pages 
  /// </summary>
  /// <param name="temppath"> Template address </param>
  /// <param name="path"> Static page address </param>
  /// <param name="t"> Data model </param>
  /// <returns></returns>
  public static bool CreateStaticPage<T>(string temppath, string path, T t)
  {
    try
    {
      // Get a template Html
      string TemplateContent = GetHtml(temppath, System.Text.Encoding.UTF8);

      // Initialization result 
      string result = string.Empty;

      // Parsing Templates to Generate Static Pages Html Code 
      result = Razor.Parse(TemplateContent, t);

      // Create a static file 
      return CreateFileHtmlByTemp(result, path);
    }
    catch (Exception e)
    {
      throw e;
    }
  }
  #endregion
}

2. Call the method (create a multithread to execute, and the effect will be better):


// Instantiate calling method 
Task tk = new Task(CreateStaticHtml);
tk.Start();
// Statically calling methods 
Task.Factory.StartNew(() => CreateStaticHtml());

3. Encapsulated static method:


/// <summary>
///  Create a static page 
/// </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);
    // Initialization result 
    string result = string.Empty;
    // Parsing Templates to Generate Static Pages Html Code 
    result = Razor.Parse(TemplateContent, view_Home);
    // Create a static file 
    Common.CreateFileHtmlByTemp(result, Server.MapPath("/Resource/Manage/Html/Home/Index.html"));
  }
}

4. If the first page is executed, you can execute a filter before executing 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. Execute the home page:


[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;
  }
}

Can let a hyperlink or jump address to jump directly to a static html page, the speed will be faster;


Related articles: