回想一下毕业到现在,也已经有5年多的时间了,虽然毕业于一个不出名的学校,但我爱好编程,毕业到现在也做了不少的管理软件,今天也来谈一谈权限的控制。 WebForm的权限控制无外乎就是用户登陆保存Session,需要权限判断的地方判断当前Session里存的用户有没有权限。 刚毕业的时候是第个页面都去判断权限,这样第个页面都要写同样的代码,虽然说Ctrl+C Ctrl+V也不累,可是如果有一个权限判断有一个地方出错了,就所有的页面都要改,所以感觉很不方便,就想一些简单的方法,上网上找一找大家都是怎么判断的,通过借鉴前辈们的方法,就有了下面的这种权限判断方法,该方法可以扩展到WebForm的所有服务器控件上。下面给大家说一下我的方法。 其实我的方法也很简单,既然每个页面都要有同样的代码,我们为什么不让他们继承于同一个类呢,别忘了面向对象的三个特点呀,封装,多态,继承。这样我们就可以写一个页面来判读权限了。 代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI; using System.Data.SqlClient; using System.Data; using Maticsoft.DBUtility; using System.Web; namespace ZLJY.Common { public class AdminBasePage : Page { BLL.RecordAction ra_bll = new BLL.RecordAction(); public AdminBasePage() { // // TODO: 在此处添加构造函数逻辑 // } protected override void OnInit(EventArgs e) { base.OnInit(e); } protected override void OnLoad(EventArgs e) { BasePage_Load(); base.OnLoad(e); } public void BasePage_Load() { if (Session["user_id"] == null || Session["user_id"].ToString() == "") { Response.Write("<html><head><title>系统安全提示</title><script>alert('为了系统安全,请重新登陆');window.top.location.href('/login.aspx');</script></head><body></body></html>"); Response.End(); } string urlpath = Request.Url.AbsolutePath; bool t = ZLJY.Web.QuanXian.CheckPage(urlpath); if (!t) { Response.Write("<html><head><title>系统安全提示</title><script>alert('您没有权限进行当前操作,请重新选择用户登陆操作');</script></head><body></body></html>"); Response.End(); } } } }
下面是权限判断的代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using System.Data; using Maticsoft.DBUtility; namespace ZLJY.Web { public static class QuanXian { public static bool CheckPage(string urlpath) { string sql = "select id from power_list where url=@url"; SqlParameter[] parmets = { new SqlParameter ("@url",SqlDbType.VarChar ,100)}; parmets[0].Value = urlpath; DataSet ds = DbHelperSQL.Query(sql, parmets); if (ds.Tables[0].Rows.Count > 0) { string powereid = ds.Tables[0].Rows[0][0].ToString(); string sql1 = "select 1 where " + powereid + " in( select power_id from czy_role_power where c_or_r=1 and cr_id=" + HttpContext.Current.Session["user_id"].ToString() + " union select a.power_id from czy_role_power a ,czy_role b where a.cr_id=b.role_id and a.c_or_r=0 and b.czy_id=" + HttpContext.Current.Session["user_id"].ToString() + ")"; DataSet ds1 = DbHelperSQL.Query(sql1); if (ds1.Tables[0].Rows.Count > 0) { return true; } else { return false; } } else { return true; } } } }
下面给大家上传一下数据库权限判断的表结构 权限列表表:


这样我们所有需要做权限判断的页面都继承于这个页面就可以了。 同样我所有的服务器控件也可能用同样的方法判断是否有权限。 好了,今天就写到这,如果有需要代码的可以给我留言。
浙公网安备 33010602011771号