zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    我这些年的项目管理心得...
    14条建议,使你的IT职业生涯更上一层楼
    手机通过WIFI连上ZXV10 H618B路由器但不能上网问题的解决
    优秀中层必备的十大能力
    IMX51启动模式
    VS2005工程由Pocket PC 2003 SDK转为WINCE6.0 SDK的问题
    VS2005工程增加SDK
    VS2005下开发PPC2003和WM50编译器一些设置
    CTO俱乐部下午茶:技术团队管理中的那些事儿
    Android通过JNI调用驱动程序(完全解析实例)
  • 原文地址:https://www.cnblogs.com/zhuhoumo/p/2849789.html
Copyright © 2011-2022 走看看