更好的code /模式用于检查存在的价值存在、模式、价值、code

2023-09-04 11:20:43 作者:渣爷!

我的web.config项如下所示。这是用于控制用户在各种角色的各种网页的访问。

Admin屏幕可以是招聘经理和CRM1访问 日志页面可以通过CRM3和受让访问

 添加键=AdminScreenRoles值=招聘经理,CRM1
添加键=LogsScreenRoles值=CRM3,受让方
 

在未来的新角色可以被赋予访问管理界面。同时新的页面可能被引入。

我需要确保当前用户有权访问在配置文件中的页面的至少一个。我有以下的code。有用。有没有更好的/简明/可扩展$ C $下此功能?

 名单,其中,串> authorizedRolesForAdmin =新的名单,其中,串>((ConfigurationManager.AppSettings [AdminScreenRoles]),斯普利特(''));
名单<字符串> authorizedRolesForLogs =新的名单,其中,串>((ConfigurationManager.AppSettings [LogsScreenRoles]),斯普利特(''));
如果((authorizedRolesForAdmin.Contains(角色名))||(authorizedRolesForLogs.Contains(角色名)))
{
    //先后获得的至少一个页面
}
 

参考

Scalable C#code从配置文件创建数组 解决方案 HelloCode打造教育赋能公益计划,让更多孩子学习更好的编程教育

您绝对可以显著简化现有的code是这样的:

  VAR hasOneRole =
    新的[] {管理员,日志}
    .SelectMany(屏幕=>(ConfigurationManager.AppSettings [屏+ScreenRoles] ??).Split(''))
    。载(角色名);
 

但是,这仍然会变得丑陋随着时间的推移。 Web.config文件只是不适合那种东西。我建议你​​把你的访问控制设置在数据库中。

I have web.config entries as shown below. This is for controlling access of users in various roles to various pages.

Admin screen can be access by Hiring Manager and CRM1 Logs screen can be access by CRM3 and Transferee

add key="AdminScreenRoles" value ="Hiring Manager,CRM1"
add key="LogsScreenRoles" value ="CRM3,Transferee "

In future new roles can be given access to Admin screen. Also new pages may be introduced.

I need to ensure that the current user has access to at least one of the pages in the config file. I have the following code. It works. Is there any better/concise/scalable code for this functionality?

List<string> authorizedRolesForAdmin = new List<string>((ConfigurationManager.AppSettings["AdminScreenRoles"]).Split(','));
List<string> authorizedRolesForLogs = new List<string>((ConfigurationManager.AppSettings["LogsScreenRoles"]).Split(','));
if ((authorizedRolesForAdmin.Contains(roleName)) || (authorizedRolesForLogs.Contains(roleName)))
{
    //Has access to at least one page
}

REFERENCE:

Scalable C# Code for Creating Array from Config File

解决方案

You can definitely significantly simplify your existing code like this:

var hasOneRole =
    new [] { "Admin", "Log" }
    .SelectMany( screen => ( ConfigurationManager.AppSettings[ screen + "ScreenRoles" ] ?? "" ).Split( ',' ) )
    .Contains( roleName );

But this is still going to get ugly over time. Web.config just isn't intended for that kind of stuff. I suggest you put your access control settings in the database.