如何从存储在 SQL 中的字符串动态映射 ClaimType

问题描述 投票:0回答:1

我在 SQL 数据库中有一个

UserClaims
表。该表存储
Id
(int)、
UserId
(int - FK)、
Type
(nvarchar) 和
Value
(nvarchar)。外键映射到
Id
表上的
User
。我目前正在使用 Dapper 从数据库中提取记录。

当检索特定

UserClaims
User
时,我希望代码是“面向未来的”,这样,如果我添加已经定义的
UserClaims
(基于
ClaimTypes中的
System.Security.Claims
静态类) 
),它们将被绘制出来并可以“本地”在代码中的其他地方引用。

目标是让这样的代码发挥作用(显然这是行不通的):

foreach(var c in user.UserClaims)
{
    if (!String.IsNullOrEmpty(c.Value) && !String.IsNullOrEmpty(c.Type))
    {
        if (c.Type == "Role")
            authClaims.Add(new Claim(ClaimTypes.Role, c.Value));
        else
        {
            var _type = typeof(ClaimTypes);
            var field = _type?.GetField(c.Type);

            if (field != null)
                authClaims.Add(new Claim(field, c.Value));
            else
                authClaims.Add(new Claim(c.Type, c.Value));
        }
    }
}

在上面的代码中,如果我可以将来自数据库的

Type
映射到
ClaimTypes
中的字段之一,那么我想使用该字段。如果没有,那么我可以创建一个自定义声明类型,我需要为其编写一些处理程序。

Role
是一个容易映射的
ClaimType
,我可以继续这种模式,或者可能实现一个开关来映射更知名的类型,但我希望我可以通过映射回来更干净地利用已经存在的功能根据他们的名字到
ClaimTypes

示例:

    authClaims.Add(new Claim(field, c.Value));
    // could be equivalent to something like:               
    authClaims.Add(new Claim(ClaimTypes.Country, "United States"));
    // stored in the UserClaims table as:
    // 5, 1, 'Country', 'United States' -- OR --
    authClaims.Add(new Claim(ClaimTypes.MobilePhone, "+11234567890"));
    // 6, 1, 'MobilePhone', '+11234567890'
.net-core asp.net-core-webapi dapper claims
1个回答
0
投票

尝试更改您的代码

var field = _type?.GetField(c.Type);

进入

 var field = _type?.GetField(c.Type).GetValue(null).ToString();
© www.soinside.com 2019 - 2024. All rights reserved.