I want to implement access control for usercontrols depending on user role(s), I want to do it on the control base class, in such way that on every user control I only need to set a string with allowed roles to see the user control
This is how an user control class may look like:
public partial class SimpleMenu : MyUsrControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
AlloweRoles = "RoleA, RoleB"
//specific user control functionality
}
}
The base class:
public abstract class MyUsrControlBase : UserControl
{
private string _allowedRoles;
protected internal string AllowedRoles
{
set
{
_allowedRoles = value;
ValidateRoles();
}
}
private ValidateRoles()
{
//Role validation logic
if (RoleHasAccess)
{
// Set user control visibility to true
}
else
{
// Set user control visibility to false
}
}
}
How to set up user control visibility from the base class depending on the validation result?
Also which event in the user control is the best to set the roles?
AlloweRoles = "RoleA, RoleB"
You can set the inherited Visible property from the base class:
EDIT: Concerning your second question, you can initialize the
AllowedRolesproperty in the derived class’ constructor, so it will be set for the whole lifespan of the user control: