• HttpHandler与HttpModule


    用HttpModule实现登陆验证:

    大家在作登录时,登录成功后,一般要把用户名放在Session中保存,在其它每一个页面的Page_Load事件中都检查Session中是否存在用户名,如果不存在就说明用户未登录,就不让其访问其中的内容。

      在比较大的程序中,这种做法实在是太笨拙,因为你几乎要在每一个页面中都加入检测Session的代码,导致难以开发和维护。下面我们看看如何使用HttpModule来减少我们的工作量

      由于在这里我们要用到Session中的内容,我们只能在AcquireRequestStatePreRequestHandlerExecute事件中编写代码,因为在HttpModule中只有这两事件中可以访问Session。这里我们选择PreRequestHandlerExecute事件编写代码。

      第一步:创建一个类库ClassLibrary。

         第二步:在Init事件中注册PreRequestHandlerExecute事件,并实现事件处理方法

    class AuthenticModule:IHttpModule
    
      {
    
      public void Dispose(){}
    
      public void Init(HttpApplication context)
    
        {
    
          context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
    
        }
    
      void context_PreRequestHandlerExecute(object sender, EventArgs e)
    
        {
    
          HttpApplication ha = (HttpApplication)sender;
    
          string path = ha.Context.Request.Url.ToString();
    
          int n = path.ToLower().IndexOf("Login.aspx");
    
      if (n == -1) //是否是登录页面,不是登录页面的话则进入{}
    
        {
    
          if (ha.Context.Session["user"] == null) //是否Session中有用户名,若是空的话,转向登录页。
    
        {
    
      ha.Context.Response.Redirect("Login.aspx?source=" + path);
    
        }
    
        }
    
      }
    
      }

    第三步:在Login.aspx页面的“登录”按钮中加入下面代码

    protected void Button1_Click(object sender, EventArgs e)
    
      {
    
        if(true) //判断用户名密码是否正确
    
       {
    
      if (Request.QueryString["source"] != null)
    
        {
    
          string s = Request.QueryString["source"].ToLower().ToString(); //取出从哪个页面转来的
    
          Session["user"] = txtUID.Text;
    
          Response.Redirect(s); //转到用户想去的页面
    
        }
    
      else
    
        {
    
          Response.Redirect("main.aspx"); //默认转向main.aspx
    
        }
    
       }
    
     }

    第四步:在Web.Conofig中注册一下这个HttpModule模块

     <httpModules>

      <add name="AuthentictModule" type="ClassLibrary.AuthentictModule,ClassLibrary"></add>

      </httpModules>

    参考文章:http://www.cnblogs.com/wxh19860528/archive/2012/07/09/2582825.html

  • 相关阅读:
    FileManager(文件管理类)
    XE6 IntraWeb.v14.0.32安装及破解指南
    在应收应付系统凭证做冲销后,如何取消冲销?
    delphi将图片保存到SQL数据库和读取图片
    去掉cxgrid 中的过滤下拉箭头
    CxGrid 分组以后自动排序了,可以禁止自动排序吗
    最简单解决CHM文件无法显示的办法
    用友T3、T6常见问题
    SQL2005还原数据库3154错误
    cxGrid 怎样才能让不自动换行 WordWrap:=false
  • 原文地址:https://www.cnblogs.com/zhuhoumo/p/2849789.html
Copyright © 2020-2023  润新知