Asp.Net中动态页面转静态页面

2017 年 11 月 17 日2870

关于在ASP.NET中动态页面转静态页面的方法网上比较多。结合实际的需求,我在网上找了一些源代码,并作修改。现在把修改后的代码以及说明写一下。

  一个是一个页面转换的类,该类通过静态函数Changfile()来实现,动态页面到静态页面的转换。  

usingSystem;
  usingSystem.Data;
  usingSystem.Configuration;
  usingSystem.Web;
  usingSystem.Web.Security;
  usingSystem.Web.UI;
  usingSystem.Web.UI.WebControls;
  usingSystem.Web.UI.WebControls.WebParts;
  usingSystem.Web.UI.HtmlControls;
  usingSystem.Text;
  usingSystem.IO;
  /**////
  ///SummarydescriptionforHtmlProxy
  ///
  publicclassHtmlProxy
  ...{
  publicHtmlProxy()
  ...{
  }
  publicstaticboolChangeFile(intid)
  ...{
  stringfilename=HttpContext.Current.Server.MapPath("Post_"+id+".html");  //尝试读取已有文件 

 Streamst=GetFileStream(filename);
  //如果文件存在并且读取成功
  if(st!=null)
  ...{
  using(st)
  ...{
  StreamToStream(st,HttpContext.Current.Response.OutputStream);
  returntrue;
  //Response.End();
  }
  }
  else
  ...{
  StringWritersw=newStringWriter();
  HttpContext.Current.Server.Execute("ForumDetail.ASPx?PID="+id,sw);
  stringcontent=sw.ToString();  //写进文件 try
  ...{
  using(FileStreamfs=newFileStream(filename,FileMode.Create,FileAccess.Write,FileShare.Write))
  ...{
  using(StreamWriterstw=newStreamWriter(fs,HttpContext.Current.Response.ContentEncoding))
  ...{
  stw.Write(content);
  }
  }
  returntrue;
  }
  catch...
  }
  }
  privatestaticStreamGetFileStream(stringfilename)
  ...{
  try
  ...{
  DateTimedt=File.GetLastWriteTime(filename);
  TimeSpants=dt-DateTime.Now;
  if(ts.TotalHours>1)
  ...{
  //一小时后过期
  returnnull;
  }
  returnnewFileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
  }
  catch...
  }
  staticpublicvoidStreamToStream(Streamsrc,Streamdst)
  ...{
  byte[]buf=newbyte[4096];
  while(true)
  ...{
  intc=src.Read(buf,0,buf.Length);
  if(c==0)
  return;
  dst.Write(buf,0,c);
  }
  }
  }
  在页面文件中,ForURL.ASPx的后台代码如下:
  protectedvoidPage_Load(objectsender,EventArgse)
  ...{
  try
  ...{
  intid=int.Parse(Request.QueryString["PID"]);
  if(HtmlProxy.ChangeFile(id))
  ...{
  Response.Redirect("Post_"+id+".html");
  }
  else
  ...{
  Response.Redirect("Post.ASPx?PID="+id);
  }
  }
  catch...{
  }
  }

0 0