1. 设计权限数据模型
示例数据库设计
sql
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Username NVARCHAR(50),
Password NVARCHAR(50)
);
CREATE TABLE Roles (
RoleID INT PRIMARY KEY,
RoleName NVARCHAR(50)
);
CREATE TABLE UserRoles (
UserID INT,
RoleID INT,
FOREIGN KEY (UserID) REFERENCES Users(UserID),
FOREIGN KEY (RoleID) REFERENCES Roles(RoleID)
);
CREATE TABLE Permissions (
PermissionID INT PRIMARY KEY,
PermissionName NVARCHAR(50)
);
CREATE TABLE RolePermissions (
RoleID INT,
PermissionID INT,
FOREIGN KEY (RoleID) REFERENCES Roles(RoleID),
FOREIGN KEY (PermissionID) REFERENCES Permissions(PermissionID)
);
CREATE TABLE Buttons (
ButtonID INT PRIMARY KEY,
ButtonName NVARCHAR(50),
PermissionID INT,
FOREIGN KEY (PermissionID) REFERENCES Permissions(PermissionID)
);
2. 获取用户权限
示例代码
csharp
public List<string> GetUserPermissions(int userID)
{
List<string> permissions = new List<string>();
// 假设有一个数据库访问类 DBAccess
using (var db = new DBAccess())
{
var userRoles = db.Query("SELECT RoleID FROM UserRoles WHERE UserID = @UserID", new { UserID = userID });
foreach (var role in userRoles)
{
var rolePermissions = db.Query("SELECT PermissionID FROM RolePermissions WHERE RoleID = @RoleID", new { RoleID = role.RoleID });
foreach (var permission in rolePermissions)
{
var button = db.QueryFirstOrDefault("SELECT ButtonName FROM Buttons WHERE PermissionID = @PermissionID", new { PermissionID = permission.PermissionID });
if (button != null)
{
permissions.Add(button.ButtonName);
}
}
}
}
return permissions;
}
3. 控制按钮权限
示例代码
csharp
public void SetButtonPermissions(Form form, List<string> permissions)
{
foreach (Control control in form.Controls)
{
if (control is Button)
{
Button button = control as Button;
if (!permissions.Contains(button.Name))
{
button.Visible = false; // 或者设置为不可用 button.Enabled = false;
}
}
else if (control.HasChildren)
{
SetButtonPermissions(control as Form, permissions);
}
}
}
4. 在窗体加载时应用权限
示例代码
csharp
private void MainForm_Load(object sender, EventArgs e)
{
int userID = GetLoggedInUserID(); // 获取当前登录用户的ID
List<string> permissions = GetUserPermissions(userID);
SetButtonPermissions(this, permissions);
}
5. 处理权限变更
示例代码
csharp
private void UpdatePermissionsButton_Click(object sender, EventArgs e)
{
int userID = GetLoggedInUserID(); // 获取当前登录用户的ID
List<string> permissions = GetUserPermissions(userID);
SetButtonPermissions(this, permissions);
}
结论
往期精品推荐: