我的需求是:
如果用户在 Login.aspx 里登录成功,我就将一个 Employe 对象实例放到会话状态中,
然后我添加了一个 Http 模块,以后用户每访问一个页面,此模块都要读取会话状态中的用户信息项,如有-则说明用户已登录,如果没有-就可能是用户直接在地址栏输入 URL 想绕开登录过程,那我就要将他重定向到登录页面。源代码片段如下:// In Login.aspx.cs (Login.aspx 的后台代码文件)
private bool Login(string strUserName, string strPassword)
{
if( 登录成功 )
{
HttpContext.Current.Session.Add( "empInfo", empInfo ); // 注1
}
}
在我的 Http 模块里,每当用户访问一个页面,我都要判断会话状态中有无 "empInfo" 项,代码片段如下:// In MyHttpModule.cs
void IHttpModule.Init( HttpApplication context )
{
context.BeginRequest += new EventHandler( context_BeginRequest );
}
void context_BeginRequest( object sender, EventArgs e )
{
// 判断用户是否已登录
if( HttpContext.Current.Session == null || HttpContext.Current.Session["empInfo"] == null ) // 注2
{
// 用户未登录,又想访问非 /Default.aspx 页面
ZMSoft.ZMHIS.WebClient.WC_Utility.GotoLoginPage( HttpContext.Current, "用户未成功登录,可能是想恶意绕开登录过程,程序准备重定向到登录页面。" );
}
}问题:
在 [注1] 那行代码处,我向会话状态添加项是成功了的,请见 [附件1]:
注意标记为 [注2] 的那行代码,他是在 [注1] 代码之后运行的(我调试过,确定),可是 HttpContext.Current.Session 一直为 NULL,我根本无法读取之前放入会话状态中的项,这是怎么回事呢?请见 [附件2]:请问:在 HttpModule 中,我该怎样正确读取先前添加到会话状态里的项?请高手指点迷津!
如果用户在 Login.aspx 里登录成功,我就将一个 Employe 对象实例放到会话状态中,
然后我添加了一个 Http 模块,以后用户每访问一个页面,此模块都要读取会话状态中的用户信息项,如有-则说明用户已登录,如果没有-就可能是用户直接在地址栏输入 URL 想绕开登录过程,那我就要将他重定向到登录页面。源代码片段如下:// In Login.aspx.cs (Login.aspx 的后台代码文件)
private bool Login(string strUserName, string strPassword)
{
if( 登录成功 )
{
HttpContext.Current.Session.Add( "empInfo", empInfo ); // 注1
}
}
在我的 Http 模块里,每当用户访问一个页面,我都要判断会话状态中有无 "empInfo" 项,代码片段如下:// In MyHttpModule.cs
void IHttpModule.Init( HttpApplication context )
{
context.BeginRequest += new EventHandler( context_BeginRequest );
}
void context_BeginRequest( object sender, EventArgs e )
{
// 判断用户是否已登录
if( HttpContext.Current.Session == null || HttpContext.Current.Session["empInfo"] == null ) // 注2
{
// 用户未登录,又想访问非 /Default.aspx 页面
ZMSoft.ZMHIS.WebClient.WC_Utility.GotoLoginPage( HttpContext.Current, "用户未成功登录,可能是想恶意绕开登录过程,程序准备重定向到登录页面。" );
}
}问题:
在 [注1] 那行代码处,我向会话状态添加项是成功了的,请见 [附件1]:
注意标记为 [注2] 的那行代码,他是在 [注1] 代码之后运行的(我调试过,确定),可是 HttpContext.Current.Session 一直为 NULL,我根本无法读取之前放入会话状态中的项,这是怎么回事呢?请见 [附件2]:请问:在 HttpModule 中,我该怎样正确读取先前添加到会话状态里的项?请高手指点迷津!
吧
{
HttpApplication app = (HttpApplication)sender;
HttpContext ctx = app.Context;
if(ctx.Session==null)
{
ctx.Response.Write("重新登录!");
}
else
{
ctx.Response.Write(uri);
}
}
web.config里添加
<add name="MyHttpModule" type="" />
或basepage,所有页面基础BasePage,实现session判断
...
......
按您的方法,改成:
if(HttpApplication.Context.Session == null)
...
......
仍然不行!注:Web.config 是配置好了的,要不然 HttpModule 根本就不会执行,我的已经执行了:
<httpModules>
<add name="HttpModule" type="ZMSoft.ZMHIS.WebClient.HttpModule, WebClient"/>
</httpModules>
正解!
非常感谢!
您是 MSDN 中文论坛的孟宪会吧?