You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并多会话实现统一权限控制?无需数据库表

Centralized Permission Management Without a Database

Great question—this is exactly the kind of repetitive, error-prone code that cries out for a centralized solution. You absolutely can consolidate all those permission checks into a single maintainable spot without creating any database tables. Here are two straightforward approaches tailored to your scenario:

1. Create a Static Permission Utility Class

This is the most direct way to lock down your permission logic in one place. You’ll define all your access rules in a static class, then call its methods wherever you need to check user access.

Step 1: Build the Utility Class

public static class PermissionManager
{
    // Centralized lists for each feature's authorized users
    private static readonly HashSet<string> Button1AuthorizedUsers = new HashSet<string>
    {
        "132", "210", "41", "103", "404", "130", "92", "490", "172"
    };

    // Add other permission sets here (e.g., Button2AuthorizedUsers, ReportAccessUsers)

    // Public methods to check access for each feature
    public static bool CanViewButton1(string userId)
    {
        if (string.IsNullOrEmpty(userId))
            return false;
        
        return Button1AuthorizedUsers.Contains(userId);
    }

    // Add corresponding methods for other features
    // public static bool CanAccessFeatureX(string userId) { ... }
}

Step 2: Replace Your Repetitive Checks

Instead of that long else if block scattered across your codebase, just call the utility method:

if (PermissionManager.CanViewButton1(Session["UserId"]?.ToString()))
{
    // Do something for button 1 access
}

Why This Works

  • Single Source of Truth: When you need to add/remove a user, you only edit the Button1AuthorizedUsers set in the PermissionManager class—no more hunting down 5-6 locations.
  • Cleaner Code: Your UI/controller logic stays focused on functionality, not messy permission lists.
  • Fast Lookups: Using a HashSet ensures quick, efficient checks and avoids duplicate user IDs.

2. Use Application Configuration (No Recompiles for Updates)

If you want to adjust permissions without rebuilding your code, store authorized user IDs in your web.config (or appsettings.json for .NET Core):

Step 1: Add Configuration Entries

In web.config:

<appSettings>
    <add key="Button1AuthorizedUsers" value="132,210,41,103,404,130,92,490,172" />
    <!-- Add other feature-specific keys here -->
</appSettings>

Step 2: Update the Utility Class to Read from Config

public static class PermissionManager
{
    private static readonly HashSet<string> Button1AuthorizedUsers;

    static PermissionManager()
    {
        // Load authorized users from config when the app starts
        var userIds = ConfigurationManager.AppSettings["Button1AuthorizedUsers"]?.Split(',') ?? Array.Empty<string>();
        Button1AuthorizedUsers = new HashSet<string>(userIds.Select(id => id.Trim()));
    }

    public static bool CanViewButton1(string userId)
    {
        if (string.IsNullOrEmpty(userId))
            return false;
        
        return Button1AuthorizedUsers.Contains(userId);
    }
}

Why This Works

  • No Recompiles: Just edit the config file and restart the app to update permissions.
  • Still Centralized: All rules live in one config section instead of being scattered across your code.

Quick Pro Tips

  • Reuse Permission Sets: If multiple features share the same user list, reuse the same HashSet instead of duplicating it.
  • Null Safety: Always validate that Session["UserId"] isn’t null before passing it to your utility methods (as shown in the examples).
  • Future-Proofing: If you eventually want to move to a database, you can just update the PermissionManager class to fetch from the DB instead of a static set/config—no changes needed to the calling code!

内容的提问来源于stack exchange,提问作者Charles Xavier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:24:14