日期:2014-05-20  浏览次数:20768 次

使用HttpModule实现用户登录检验的问题
网上有很多资料说明自定义一个验证类实现IHttpModule接口来实现基本的用户登录验证功能,代码如下:
  public class UserAuthorizationModule:IHttpModule
  {
  #region IHttpModule 成员

  public void Dispose()
  {
  }

  public void Init(HttpApplication context)
  {
  context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
  }

  void context_AcquireRequestState(object sender, EventArgs e)
  {
  HttpApplication application = (HttpApplication)sender;

  //检查用户是否已经登录
  if (application.Context.Session["UserID"] == null || application.Context.Session["UserID"].ToString().Trim()=="")
  {
  // 获取Url
  string requestUrl = application.Request.Url.ToString();
  string requestPage = requestUrl.Substring(requestUrl.LastIndexOf('/') + 1);

  // 如果请求的页面不是登录页面,则重定向到登录页面。
  if(requestPage!="Login.aspx")
  {
  application.Server.Transfer("Login.aspx");
  }
  }
  }

  #endregion
  }
我把这个UserAuthorizationModule类放在Web项目WebApp下的Common文件夹下,并且在web.config文件中添加httpModules配置节
<httpModules>
<add type="WebApp.UserAuthorizationModule" name="UserAuthorizationModule"/>
</httpModules>
首次访问测试页面Test.aspx能跳转到Login.aspx页,但是Login.aspx页面中的图片不能加载,并且报js错误(Login页面中有简单的js判断语句),请问各位大大是什么原因造成的啊

------解决方案--------------------
图片加载是不是图片路径错误了。js报错说明js有问题撒,可能问题没有考虑周全。贴上代码有助于帮你更容易的找到问题!
------解决方案--------------------
估计事你爹login 和test page 不在同一级目录,transfer之后 浏览器不知道目录已经改变,
用 redirect 应该就可以吧,要么 login 页面上用绝对路径或者 动态改变路径咯
 楼主结贴率不高啊,呵呵
------解决方案--------------------
楼主这样写 server.transfer("~/login.asxp")
------解决方案--------------------
你要了解一下页面加载的流程,页面上的每一个图片的加载都需要发起一次web request的,也就是说login页面加载的同时,他上面的js和图片也在加载,所以我建议你把图片和js放在指定的目录下,在你的IHttpModule实现类里跳过对这些目录下文件请求的的检查。
------解决方案--------------------
C# code

  void context_AcquireRequestState(object sender, EventArgs e)
  {
      HttpApplication application = (HttpApplication)sender;

      HttpApplication application = sender as HttpApplication;

      //
      // 获得请求 URL
      //
      string path = application.Context.Request.Url.ToString();
      
      //
      // 检查是否是对 aspx 页面的请求,注意:对 js, css, 图片的请求也将由 HttpModule 处理
      //
      if(path.ToLower().IndexOf(".aspx")==-1)
      {
          return;
      }

      //检查用户是否已经登录
      if (application.Context.Session["UserID"] == null ||  application.Context.Session["UserID"].ToString().Trim()=="")
      {
          // 获取Url
          string requestUrl = application.Request.Url.ToString();
          string requestPage = requestUrl.Substring(requestUrl.LastIndexOf('/') + 1);

          // 如果请求的页面不是登录页面,则重定向到登录页面。
          if(requestPage!="Login.aspx")
          {
              application.Server.Transfer("Login.aspx");
          }
      }
  }