遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

Asp.net中内容页的静太生成

场景
用户发表一条信息后,要将这条信息生成静太页面(.html),以前的做法可能是使用模版替换标签的方法,或者通过http协议去申请对应显示页的处理程序(比方detail.asp?id=3)获取html代码后再将其保存成.html文件.
在asp.net里我们可以使用Page类的public override void ProcessRequest(HttpContext context); 方法来完成这个任务.
比如内容显示页为Detail.aspx?Id=编号,信息添加页为Add.aspx,那么我们首先在Add.aspx页中添加对Detail.aspx的引用<%@ Reference Page="~/Detail.aspx" %>,这样你就可以在代码中使用类detail__aspx.
下面生成信息编号为5的静太页
代码
        detail_aspx page = new detail_aspx();
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HttpRequest req = new HttpRequest("", "http://wdfrog.cnblogs.com/", "id=5");
        HttpResponse res = new HttpResponse(sw);
        page.ProcessRequest(new HttpContext(req, res));
        string html=sw.ToString();
        sw.Close();
        WriteToFile("5.html",html);
注意点
开始时我在Detail.aspx页中获取参数的方法是HttpContext.Current.Request["ID"].
在这里HttpContext.Current.Request获取的是Add.aspx页的QueryString,所以参数传递不过去,改成Request["ID"]就好了.

protected override void Render(HtmlTextWriter writer)
    {
      if(Request["html"]==true){
        System.IO.StringWriter html = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter tw = new HtmlTextWriter(html);
        base.Render(tw);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("index.htm"), false, System.Text.Encoding.Default);
        sw.Write(html.ToString());
        sw.Close();
        tw.Close();
        }else{
          base.Render(writer)

        }

//如何在静态页中更新信息,这就需要用户自己更新。在页面上方添加

        这儿写上Response.Redirect("index.htm");//表明每次加载首页动态页时都是重写index.aspx页面重写后重定向到Index.htm
     }

posted on 2008-01-04 16:00  遗忘海岸  阅读(315)  评论(0编辑  收藏  举报