【发布时间】:2013-12-10 17:27:59
【问题描述】:
ASP.NET 4.5 / C# / SQL 2012
我已经有一个定义明确的数据库,其中包含一个用户表和一个角色/权限列。该列包含一个分隔的角色列表。我希望在后端使用 ASP.NET 的内置功能,这样我就可以偷懒并使用 and filter by role 之类的东西。我想从数据库中读取我的角色并告诉 ASP 这些是我的用户所在的角色。自定义...但希望很简单。这是我目前所拥有的:
//create an identity
GenericIdentity objIdentity = new GenericIdentity("Matt"); //this would actually be the username/email of the newly authenticated user
//get roles for user
string[] strRoles = { "ADW", "USR" }; //this will get read from the database on authentication
//add identity and roles to a principal
GenericPrincipal objPrincipal = new GenericPrincipal(objIdentity, strRoles);
//add to current user
HttpContext.Current.User = objPrincipal;
//add the principal to the current context of the current thread
Thread.CurrentPrincipal = objPrincipal; //not sure what this does, doesn't affect my results/tests
如果我执行上面的代码,然后运行以下代码:
Response.Write(User.IsInRole("ADW"));
Response.Write(User.IsInRole("xxx"));
我得到了预期的真/假。但是,这不会持续到下一页。我对自定义会员/角色提供者进行了大量阅读,但我找不到这个特定的用例。大多数人谈论专门为此任务设置数据库。我还看到提到了较新的 Simple Membership,但也无法从中获得任何爱。我希望有一个解决方案涉及我已经在做的事情。我很想在用户进行身份验证时执行此代码,但能够在其他页面中引用此用户。我总是可以为每一页调用数据库。我假设那会很糟糕,而且内置提供程序不是这样做的。
谢谢大家。
【问题讨论】:
标签: asp.net asp.net-membership