权限管理-页面访问限制 —— HttpModule
场景
1、某应用系统需页面访问限制功能,即:输入网址,先进行权限判断,验证通过则显示相应内容,否则提示错误
2、应用系统存在N个页面
方案
1、权限管理方法+每个页面的Page_Load事件中调用,代码量极大,且修改困难!悲剧,哥经历过它的苦
(100多张页面啊~)
2、Page基类重写OnOnit,方法中调用权限验证,作者同样用过
3、HttpModule集中处理页面访问,酷!
页面访问分三类:所有用户可见(登陆页Login.aspx),登陆用户可见(首页Home.aspx),具备某权限的用户可见
代码
public class PageVerify : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
//session可用
context.PostAcquireRequestState += new System.EventHandler(Verify);
}
public void Verify(object sender, EventArgs e)
{
HttpApplication httpApplication = (HttpApplication)sender;
//当前页面 权限类型:皆可访问,登陆用户,具备某权限的登陆用户
string currentUrl = httpApplication.Context.Request.Url.AbsolutePath.Split('/')[1];
int level= GetPageLevel(currentUrl);
if (level> 0)
{
if (httpApplication.Context.Session["User"]!=null)
{
if (level== 2)
{
//是否具备权限(用户ID,页面ID)
httpApplication.Context.Response.Write("对不起,您不具备访问此页面的权限!请与管理员联系");
}
}
else
{
//未登录!
httpApplication.Context.Response.Write("对不起,您访问的页面需登录才可见,请登录!");
}
}
}
private int GetPageLevel(string url)
{
if (url == "home.aspx")
{
return 1;
}
else if (url == "detail.aspx")
{
return 2;
}
return 0;
}
}
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
//session可用
context.PostAcquireRequestState += new System.EventHandler(Verify);
}
public void Verify(object sender, EventArgs e)
{
HttpApplication httpApplication = (HttpApplication)sender;
//当前页面 权限类型:皆可访问,登陆用户,具备某权限的登陆用户
string currentUrl = httpApplication.Context.Request.Url.AbsolutePath.Split('/')[1];
int level= GetPageLevel(currentUrl);
if (level> 0)
{
if (httpApplication.Context.Session["User"]!=null)
{
if (level== 2)
{
//是否具备权限(用户ID,页面ID)
httpApplication.Context.Response.Write("对不起,您不具备访问此页面的权限!请与管理员联系");
}
}
else
{
//未登录!
httpApplication.Context.Response.Write("对不起,您访问的页面需登录才可见,请登录!");
}
}
}
private int GetPageLevel(string url)
{
if (url == "home.aspx")
{
return 1;
}
else if (url == "detail.aspx")
{
return 2;
}
return 0;
}
}
AcquireRequestState事件,当实际服务请求的处理程序获得与该请求关联的状态信息时发生,在这个事件发生时才能取到Session中信息。
BeginRequest事件在AcquireRequestState之前发生,我们把取Session状态的代码放在BeginRequest中肯定是取不到的。
参考资料
http://www.cnblogs.com/stwyhm/archive/2006/08/09/471729.html
浙公网安备 33010602011771号