.net core 在代码中使用jwt token中的用户信息

参考:https://www.it1352.com/2599186.html

1. 声明Claim数组

Claim[] myClaims = new Claim[] {
new Claim("UserNo", "1"), //自定义
new Claim(ClaimTypes.Role,"User"), //系统预设
};

  

2.取Claim值

var Role = User.Claims.Where(x => x.Type == ClaimTypes.Role).FirstOrDefault()?.Value;
var UserNo = User.Claims.FirstOrDefault(c => c.Type == "UserNo");
var Email = User.FindFirst("Email")?.Value; var claimsIdentity = this.User.Identity as ClaimsIdentity; var Name = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value; string Identifier = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

  

 

C#类拓展方法  

  

 调用:

Test test = new Test();
test.Name = "hello";
ApiExtension.POST(test, (p =>
{
    string json = p;
}));

  

  

对象装字典帮助类

/// <summary>
    /// 对象装字典帮助类
    /// </summary>
    public static class ModelToDictionaryHelper
    {
        /// <summary>
        /// 第一种通过反射进行转换
        /// </summary>
        /// <typeparam name="T">要转换的类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static Dictionary<string, string> ModelToDic<T>(this T obj) where T : class
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            if (obj == null)
            {
                return map;
            }
            Type t = obj.GetType();
            PropertyInfo[] PropertyList = t.GetProperties();
            foreach (var item in PropertyList)
            {
                string name = item.Name;
                object value = item.GetValue(obj, null);
                if (value != null)
                {
                    map.Add(name, value.ToString());
                }
                else
                {
                    map.Add(name, "");
                }
            }
            return map;
        }

        /// <summary>
        /// 借助JsonConvert快速实现转换
        /// </summary>
        /// <typeparam name="T">要转换的类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static Dictionary<string, string> ModelToDic2<T>(this T obj) where T : class
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            if (obj == null)
            {
                return map;
            }
            var objstr = JsonConvert.SerializeObject(obj);
            //string(json) 转 Dictionary
            map = JsonConvert.DeserializeObject<Dictionary<string, string>>(objstr);
            return map;
        }
    }

  

posted @ 2022-12-15 15:50  microsoft-zhcn  阅读(34)  评论(0编辑  收藏  举报