ASP.NET MVC產生靜態頁面

來源:互聯網
上載者:User

標籤:set   []   path   web   attr   substr   catch   client   pos   

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

 

ASP.NET MVC產生靜態頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.