c#一般处理程序替换html内容

1、在html写一个占位符,含有特殊符号,以免替换其他内容 如:@errorInfo

 <!--此处提示登录错误信息-->
        @errorInfo

2、把一般处理程序中设置响应内容类型为html

 context.Response.ContentType = "text/html";//虽然是以c#操作,但本质是改变了HTTP协议

3、//读取模版UserList.htm内容

   string temp = File.ReadAllText(context.Server.MapPath("UserList.html"));

读取文件的所有内容:File.RedAllText(String path);
注意:在读写服务器磁盘文件的时候一定要提供绝对路径,不能写相对路径
注意:context.Server.MapPath(“UserList.html”);//返回相对路径转换成绝对路径

4、将占位符替换成需要替换的字符串

   temp = temp.Replace("@errorInfo", "用户名或密码错误");

5、返回html模板

    context.Response.Write(temp);

但是在实际登录过程中,如果用户第一次进入登录页面时,占位符会直接以字符串的方式显示@errorInfo,所以需要通过在html中添加一个隐藏域判断用户是否第一次进入登录页面

 <input type="hidden" name="isPostBack" value="true"/>

所以最终代码为

context.Response.ContentType = "text/html";
           //判断是否第一次登录
           string isPostBack = context.Request["isPostBack"];
           //读取模版UserList.htm内容
           string temp = File.ReadAllText(context.Server.MapPath("Login.html"));
           if (string.IsNullOrEmpty(isPostBack))
           {
               //第一次登录,把占位符设置为空
               temp = temp.Replace("@errorInfo", "");
               context.Response.Write(temp);
           }
           else
           {
               //不是第一次登录,填写数据后登录
               string Name = context.Request["Name"];
               string Pwd = context.Request["Pwd"];
               bool flag = new UserService().GetCountByNameAndPwd(new User { Name = Name, Pwd = Pwd });
               if (flag)
               {
               //成功登录
                   UserList u = new UserList();
                   u.ProcessRequest(context);
               }
               else
               {
               //登录错误
                   temp = temp.Replace("@errorInfo", "用户名或密码错误!");
                   context.Response.Write(temp);
               }
           }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值