Five options for generating static pages

plan 1:

/// <summary>
/// 传入URL返回网页的html代码
/// </summary>
/// <param name="Url">URL</param>
/// <returns></returns>
public static  string getUrltoHtml(string Url)
{
errorMsg = "";
try
{
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
// Get the response instance.
System.Net.WebResponse wResp =wReq.GetResponse();
// Read an HTTP-specific property
//if (wResp.GetType() ==HttpWebResponse)
//{
//DateTime updated  =((System.Net.HttpWebResponse)wResp).LastModified;
//}
// Get the response stream.
System.IO.Stream respStream  = wResp.GetResponseStream();
// Dim reader As StreamReader = New StreamReader(respStream)
System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("gb2312"));
return  reader.ReadToEnd();

}
catch(System.Exception ex)
{
errorMsg = ex.Message ;
}
return "";
}

You can use this function to get the html code of the client side of the web page, and then save it to a .html file.

Scenario 2:

It is not difficult to generate a single static page, but how to keep the associations and links between the static pages intact; especially when the pages are frequently updated, modified, or deleted;

Like Alibaba's pages are all html, it is estimated that the function of address mapping is used. For address mapping, please refer to: http://www.easewe.com/Article/ShowArticle.aspx?article=131

You can take a look at this page to analyze his "bidding countdown" function http://info.china.alibaba.com/news/subject/v1-s5011580.html?head=top4&Bidding=home5

ASP.Net generates static HTML pages The FileSystemObject object used to generate static pages implemented
in Asp!
In .Net, System.IO is involved in such operations. The
following is the program code Note: This code is not original! Refer to other people's code

//生成HTML页
  public static bool WriteFile(string strText,string strContent,string strAuthor)
  {
   string path = HttpContext.Current.Server.MapPath("/news/");
   Encoding code = Encoding.GetEncoding("gb2312");
   // 读取模板文件
   string temp = HttpContext.Current.Server.MapPath("/news/text.html");
   StreamReader sr=null;
   StreamWriter sw=null;
   string str=""; 
   try
   {
    sr = new StreamReader(temp, code);
    str = sr.ReadToEnd(); // 读取文件
   }
   catch(Exception exp)
   {
    HttpContext.Current.Response.Write(exp.Message);
    HttpContext.Current.Response.End();
    sr.Close();
   }
   string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
   // 替换内容
   // 这时,模板文件已经读入到名称为str的变量中了
   str =str.Replace("ShowArticle",strText); //模板页中的ShowArticle
   str = str.Replace("biaoti",strText);
   str = str.Replace("content",strContent);
   str = str.Replace("author",strAuthor);
   // 写文件
   try
   {
    sw = new StreamWriter(path + htmlfilename , false, code);
    sw.Write(str);
    sw.Flush();
   }
   catch(Exception ex)
   {
    HttpContext.Current.Response.Write(ex.Message);
    HttpContext.Current.Response.End();
   }
   finally
   {
    sw.Close();
   }
   return true;
   此函数放在Conn.CS基类中了在添加新闻的代码中引用 注:工程名为Hover

    if(Hover.Conn.WriteFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString)))
    {
     Response.Write("添加成功");
    }
    else
    {
     Response.Write("生成HTML出错!");
    } 

Template page Text.html code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
  <title>ShowArticle</title>
   <body>
    <h1>title</h1>
      <br/>
      content
      <br/>
      author
</body>
</HTML>

After the prompt is added successfully, an html file with the current time as the file name will be generated! The above only writes the passed parameters directly into the HTML file. In practical applications, the database needs to be added first, and then the HTML file is written.

Scenario 3 : Example for a client reference (SJ)

Its function is to obtain the code of a page in a client-side way, and then it can be used for other purposes. In this example, it is directly output

<script>
    var oXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    oXmlHttp.open("GET","http://www.webjx.com", false);
    oXmlHttp.send()
    var oStream = new ActiveXObject("ADODB.Stream");
    if(oStream == null)
        alert("您的机器不支持ADODB.Stream.")
    else
    {
        oStream.Type=1;
        oStream.Mode=3;
        oStream.Open() ;
        oStream.Write(oXmlHttp.responseBody);
        oStream.Position= 0;
        oStream.Type= 2;
        oStream.Charset="gb2312";
        var result= oStream.ReadText();
        oStream.Close();
        oStream = null;
        var aa = window.open("","")
        document.write(result);
        aa.document.write(result);
    }
</script>

Option 4: The same as learning csdn. Use xml to save data, and there is only one file for the template XSL.

Use xml to save data, use xsl to define templates and generate data. You can easily display data on the client or service segment through xsl. It's even easier if you want to generate static foliage. Go to check the xml class package of .net to solve the problem.

Advantages: It can be easily and quickly converted into the format and content you want.
Disadvantages: Need to learn more content, not easy to get started.

Scenario 5:

Idea one:

  1. Use tools such as Dw-Mx to generate templates in html format, and add special tags (such as h t m l format ), use the code to read this template when dynamically generating the file, then obtain the content input in the foreground, add it to the marked position of this template, generate a new file name and write it to the disk, and then write the relevant data to the database after writing.
  2. To hardcode Html files with code behind, you can use the HtmlTextWriter class to write html files.

advantage:

  1. Very complex pages can be created. By using the method of including js files, adding the document.write() method to the js file can add content such as page headers and advertisements to all pages.

  2. The static html file can use the Index Server of MS Windows2000 to build a full-text search engine, and use asp.net to get the search results in the form of DataTable. The Index service of Win2000 cannot find the content of the xml file. This search function is very powerful if you include a database search and an index double lookup.

  3. Save server load, requesting a static html file saves a lot of server resources than an aspx file.

shortcoming:

Idea 2: If the hard-coding method is used, the workload is very large, and a lot of html code is required. Debugging is difficult. Moreover, the html style generated by hard coding cannot be modified. If the website changes the style, it must be re-coded, which will bring huge workload to the later stage.

Therefore, the first approach is adopted here

Listing code

1. Define (template.htm) html template page

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body >
<table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing ="0" bgcolor="#eeeeee" style="border:1px solid #000000">
<tr>
<td width="100%" valign="middle" align="left">
<span style="color: $htmlformat[1];font-size: $htmlformat[2]">$htmlformat[3]</span>
</td>
</tr>
</table>
</body>
</html>

2.asp.net code:

//---------------------读html模板页面到stringbuilder对象里----

string[] format=new string[4];//定义和htmlyem标记数目一致的数组
StringBuilder htmltext=new StringBuilder();
try
{
    using (StreamReader sr = new StreamReader("存放模板页面的路径和页面名"))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            htmltext.Append(line);
        }
        sr.Close();
    }
}
catch
{
    Response.Write("<Script>alert('读取文件错误')</Script>");
}
//---------------------给标记数组赋值------------
format[0]="background="/blog/bg.jpg"";//背景图片
format[1]= "#990099";//字体颜色
format[2]="150px";//字体大小
format[3]= "<marquee>生成的模板html页面</marquee>";//文字说
//----------替换htm里的标记为你想加的内容
for(int i=0;i<4;i++)
{
    htmltext.Replace("$htmlformat["+i+"]",format[i]);
}
//----------生成htm文件------------------――
try
{
    using(StreamWriter sw=new StreamWriter("存放路径和页面名",false,System.Text.Encoding.GetEncoding("GB2312")))    
    {
        sw.WriteLine(htmltext);
        sw.Flush();
        sw.Close();
    }
}
catch
{
    Response.Write ("The file could not be wirte:");
} 


Summary This method can easily generate html files. The program uses cyclic replacement, so it is very fast for templates that need to replace a large number of elements.

Reprinted from: http://www.cnblogs.com/Gavinzhao/archive/2010/03/24/1693672.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326011163&siteId=291194637