WEB页面统一认证登录方法
在每一个页面的aspx.cs文件中都要写代码检查用户是否已登录,麻烦。这样子来做比较好。
先建一个测试用解决方案吧,WebApplication1
新建一个类,就叫LoginModule好了,继承 IHttpModule 接口,内容差不多是这样子:
1
using System;
2
using System.Web;
3
using System.Web.Handlers ;
4
5
namespace WebApplication1
6
{
7
/// <summary>
8
/// LoginModule 的摘要说明。
9
/// </summary>
10
public class LoginModule : IHttpModule
11
{
12
public LoginModule()
13
{
14
//
15
// TODO: 在此处添加构造函数逻辑
16
//
17
}
18
19
private void context_AcquireRequestState(object sender, EventArgs e)
20
{
21
HttpContext context = HttpContext.Current;
22
try
23
{
24
//把不需要验证的Handler加在这里
25
if (context.Handler is TraceHandler)
26
{
27
return;
28
}
29
if(context.Session["Session_User"] == null)
30
{
31
string curUrl = context.Request.Url.ToString();
32
33
string currUser = "";
34
// 用户登录检查代码
35
// 



.
36
37
if(currUser == null || currUser.Trim().Length == 0)
38
throw new Exception("你还不是本系统的用户,如果需要进行本系统的操作,请联系管理员");
39
else
40
context.Session["Session_User"] = currUser;
41
}
42
}
43
catch (Exception ex)
44
{
45
throw ex;
46
}
47
}
48
49
public void Init(HttpApplication context)
50
{
51
context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
52
}
53
54
public void Dispose()
55
{
56
57
}
58
}
59
}
60
using System;2
using System.Web;3
using System.Web.Handlers ;4

5
namespace WebApplication16
{7
/// <summary>8
/// LoginModule 的摘要说明。9
/// </summary>10
public class LoginModule : IHttpModule 11
{12
public LoginModule()13
{14
//15
// TODO: 在此处添加构造函数逻辑16
//17
}18

19
private void context_AcquireRequestState(object sender, EventArgs e)20
{21
HttpContext context = HttpContext.Current;22
try23
{24
//把不需要验证的Handler加在这里25
if (context.Handler is TraceHandler)26
{27
return;28
}29
if(context.Session["Session_User"] == null)30
{31
string curUrl = context.Request.Url.ToString();32

33
string currUser = "";34
// 用户登录检查代码35
// 



.36

37
if(currUser == null || currUser.Trim().Length == 0)38
throw new Exception("你还不是本系统的用户,如果需要进行本系统的操作,请联系管理员");39
else40
context.Session["Session_User"] = currUser;41
}42
}43
catch (Exception ex)44
{45
throw ex;46
}47
}48

49
public void Init(HttpApplication context)50
{51
context.AcquireRequestState += new EventHandler(context_AcquireRequestState);52
}53

54
public void Dispose()55
{56
57
}58
}59
}60

然后再在 Web.Config 中增加如下设置。
<configuration>
<system.web>
<httpModules>
<add name="LoginModule" type="WebApplication1.LoginModule, WebApplication1" />
</httpModules>
</system.web>
</configuration>这样就把登录认证的操作统一在LoadModule中进行处理啦。省掉好多工作量 :)

浙公网安备 33010602011771号