ASP.NET靜態頁產生方法_實用技巧

來源:互聯網
上載者:User

本文執行個體講述了ASP.NET靜態頁產生方法。分享給大家供大家參考。具體實現方法如下:

一、問題:

由於業務需要,得把頁面按照模板頁產生靜態頁面,所以自己就琢磨了下,寫些思路,以備日後需要的時候用。

二、解決方案:

靜態頁產生用到最多的就是匹配跟替換了,首先得讀模數板頁的html內容,然後進行你自己定義的標籤匹配,比如說我要把我定義的標題標籤換成讀取資料庫的標題內容,那麼可以直接讀取資料庫的標題,然後直接進行替換,然後產生html檔案就OK了。

具體代碼如下:

複製代碼 代碼如下:
/// <summary>
/// 解析模板的html中匹配的標籤,進行替換(暫時只能用於沒有分頁的頁面)
/// </summary>
/// <param name="html">HTML</param>
/// <returns>返回替換後的HTML</returns>
public static string ReturnHtml(string html)
{
    string newhtml = html;
    newhtml = newhtml.Replace("<#Title#>", "這個是標題替換");//替換標題
    //newhtml = newhtml.Replace("<#Content#>", "這個是內容替換");//替換標題
    newhtml = CreateList(newhtml);
    return newhtml;
}

/// <summary>
/// 讀取HTML檔案
/// </summary>
/// <param name="temp">html檔案的相對路徑</param>
/// <returns>返回html</returns>
public static string ReadHtmlFile(string temp)
{
    StreamReader sr = null;
    string str = "";
    try
    {
 sr = new StreamReader(HttpContext.Current.Server.MapPath(temp), code);
 str = sr.ReadToEnd(); // 讀取檔案
    }
    catch (Exception exp)
    {
 HttpContext.Current.Response.Write(exp.Message);
 HttpContext.Current.Response.End();
    }
    finally
    {
 sr.Dispose();
 sr.Close();

    }
    return str;
}

/// <summary>
/// 產生html檔案
/// </summary>
/// <param name="filmname">檔案名稱(帶相對路徑路徑,如:../a.html)</param>
/// <param name="html">html內容(整個)</param>
public static void writeHtml(string filmname, string html)
{
    System.Text.Encoding code = System.Text.Encoding.GetEncoding("utf-8");
    string htmlfilename = HttpContext.Current.Server.MapPath(filmname);
    string str = html;
    StreamWriter sw = null;
    // 寫檔案
    try
    {
 sw = new StreamWriter(htmlfilename, false, code);
 sw.Write(str);
 sw.Flush();
    }

    catch (Exception ex)
    {
 HttpContext.Current.Response.Write(ex.Message);
 HttpContext.Current.Response.End();
    }

    finally
    {
 sw.Close();
    }
}

從代碼可以看得出來,產生靜態頁面其實就是這麼一個過程:讀模數板頁的源碼->匹配替換自訂的標籤為實際內容->最後再產生新的html檔案,思路就這麼走,以前沒有動手過,覺得太複雜了,如今主動寫的時候,發現也不算很複雜。

最後,如果說有些產生分頁列表的,也就是把列表頁面進行迴圈產生,有多少頁就產生多少個靜態頁檔案,如果有不懂的可以回複問,我懂的我盡量為大家解答,當然,不懂的我也無能為力了,畢竟我也是剛接觸這功能,現在暫時弄得一個最簡陋的樣子,附圖上來給大家笑話笑話:

希望本文所述對大家的asp.net程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.