HttpHandler与HttpModule

用HttpModule实现登陆验证:

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

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

  由于在这里我们要用到Session中的内容,我们只能在AcquireRequestState和PreRequestHandlerExecute事件中编写代码,因为在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

转载于:https://www.cnblogs.com/zhuhoumo/archive/2013/01/07/2849789.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值