ASP.NET MVC生成靜態頁面


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的靜態頁面,速度會更快;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM