欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.Net 动态页面转静态页面主要代码

程序员文章站 2024-03-09 11:00:23
一个是一个页面转换的类,该类通过静态函数changfile()来实现,动态页面到静态页面的转换。   复制代码 代码如下: using system;   using sy...
一个是一个页面转换的类,该类通过静态函数changfile()来实现,动态页面到静态页面的转换。  
复制代码 代码如下:

using system;
  using system.data;
  using system.configuration;
  using system.web;
  using system.web.security;
  using system.web.ui;
  using system.web.ui.webcontrols;
  using system.web.ui.webcontrols.webparts;
  using system.web.ui.htmlcontrols;
  using system.text;
  using system.io;
  /**////
  /// summary description for htmlproxy
  ///
  public class htmlproxy
  ...{
  public htmlproxy()
  ...{
  }
  public static bool changefile(int id)
  ...{
  string filename = httpcontext.current.server.mappath("post_" + id + ".html");
  //尝试读取已有文件   stream st = getfilestream(filename);
  //如果文件存在并且读取成功
  if (st != null)
  ...{
  using (st)
  ...{
  streamtostream(st, httpcontext.current.response.outputstream);
  return true;
  //response.end();
  }
  }
  else
  ...{
  stringwriter sw = new stringwriter();
  httpcontext.current.server.execute("forumdetail.aspx?pid=" + id, sw);
  string content = sw.tostring();
  //写进文件

 try
  ...{
  using (filestream fs = new filestream(filename, filemode.create, fileaccess.write, fileshare.write))
  ...{
  using (streamwriter stw = new streamwriter(fs, httpcontext.current.response.contentencoding))
  ...{
  stw.write(content);
  }
  }
  return true;
  }
  catch ...{ return false; }
  }
  }
  private static stream getfilestream(string filename)
  ...{
  try
  ...{
  datetime dt = file.getlastwritetime(filename);
  timespan ts = dt - datetime.now;
  if (ts.totalhours >1)
  ...{
  //一小时后过期
  return null;
  }
  return new filestream(filename, filemode.open, fileaccess.read, fileshare.read);
  }
  catch ...{ return null; }
  }
  static public void streamtostream(stream src, stream dst)
  ...{
  byte[] buf = new byte[4096];
  while (true)
  ...{
  int c = src.read(buf, 0, buf.length);
  if (c == 0)
  return;
  dst.write(buf, 0, c);
  }
  }
  }
  在页面文件中,forurl.aspx的后台代码如下:
  protected void page_load(object sender, eventargs e)
  ...{
  try
  ...{
  int id = int.parse(request.querystring["pid"]);
  if(htmlproxy.changefile(id))
  ...{
  response.redirect("post_" + id + ".html");
  }
  else
  ...{
  response.redirect("post.aspx?pid=" + id );
  }
  }
  catch ...{
  }
  }