欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-18 15:56:06
本文主要讲述了在asp.net mvc中,页面静态化的方法。对于网站来说,生成纯html静态页面除了有利于seo外,还可以减轻网站的负载能力和提高网站性能。 1.先付...

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

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