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

  • 相关阅读:
    共享内存
    利用消息队列实现ECHO_SRV
    LINUX学习:System V消息队列
    linux:利用socketpair来在进程间传递描述符
    react传参
    ajax、axios、fetch
    js 深拷贝和浅拷贝实现
    css----px、rem、em、vw、vh、vm
    Sass、Less 和 Stylus区别
    箭头函数和普通函数对比
  • 原文地址:https://www.cnblogs.com/zhuhoumo/p/2849789.html
Copyright © 2011-2022 走看看