遗忘海岸

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

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   遗忘海岸  阅读(333)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示