在我的应用程序中,每个用户只有一个clientid
但有多个roles
。
例如,用户John的clientid
= 1且roles
= userx,userz
我想要实现的是隐藏或显示我的应用程序对用户的clientid
和role
我的数据库中有这个数组:
[dbo].[MyMenus](
[id] [int] IDENTITY(1,1) NOT NULL,
[controlid] [nvarchar](500) NULL,
[clientid_available] [nvarchar](50) NULL,
[clientid_hidden] [nvarchar](50) NULL,
[role_available] [nvarchar](500) NULL,
[role_hidden] [nvarchar](500) NULL
其中clientid_available,clientid_hidden,role_available,role_hidden包含以逗号分隔的值。如果控件具有clientid_available,则clientid_hidden为null,反之亦然。对于role_available和role_hidden
也是如此示例:0 | Control1 | 0,1 | null | userx | null
这意味着具有clientid 0,1的用户和userx角色的用户可以看到Control
以下是我的代码:
var hiddenControls = from c in dc.MyMenus
where c.clientid_hidden != null || c.role_hidden != null
select c;
var visibleControls = from c in dc.MyMenus
where c.clientid_available != null || c.clientid_available != null
select c;
foreach (var c in hiddenControls)
{
if (c.clientid_hidden != null)
{
if (c.clientid_hidden.Contains(clientId.ToString()))
(this.Page.FindControl(c.controlid)).Visible = true;
else
(this.Page.FindControl(c.controlid)).Visible = false;
}
//Code for role handling
}
foreach (var c in visibleControls)
{
if (c.clientid_available != null)
{
if (c.clientid_available.Contains(clientId.ToString()))
(this.Page.FindControl(c.controlid)).Visible = true;
else
(this.Page.FindControl(c.controlid)).Visible = false;
}
//Code for role handling
}
但我不知道角色处理的逻辑。由于role_available
,role_hidden
可以有多个以','分隔的值,因此当前用户可以有多个角色Roles.GetRolesForUser(HttpContext.Current.User.ToString())
答案 0 :(得分:0)
我不确定我是否完全理解这个问题,这看起来非常糟糕......但我认为你在寻找:
var userroles = Roles.GetRolesForUser(HttpContext.Current.User.ToString());
if (c.role_available.Split(',').Any(cr => userroles.Any(ru => ru.RoleName== cr)))
{
(this.Page.FindControl(c.controlid)).Visible = true;
}
else{
(this.Page.FindControl(c.controlid)).Visible = false;
}
答案 1 :(得分:0)
您可以使用:
Roles.IsUserInRole
try
{
if (!Roles.IsUserInRole(User.Identity.Name, "Administrators"))
{
Msg.Text = "You are not authorized to view user roles.";
UsersListBox.Visible = false;
return;
}
}
catch (HttpException e)
{
Msg.Text = "There is no current logged on user. Role membership cannot be verified.";
return;
}
Roles.IsUserInRole Method(String)
https://msdn.microsoft.com/en-us/library/4z6b5d42(v=vs.110).aspx
答案 2 :(得分:0)
我使用Intersect
使用此代码:
string[] roles = Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name);
if (c.role_hidden.Split(',').Intersect(roles).Any())
{
(this.Page.FindControl(c.controlid)).Visible = false;