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

C#中从Identity User模型获取属性值遇类型不匹配错误

解决“Object does not match target type”错误,获取Identity User实例的属性值

问题根源

你传入GetAttribute方法的是typeof(Users)(Type类型对象),但PropertyInfo.GetValue()需要的是具体的用户实例对象,不是类型本身,这就是报错的核心原因。

修改方案

  1. 调整GetAttribute方法的参数,接收具体的Users实例而非Type
  2. 控制器调用时传入从数据库查询到的users实例
  3. 处理属性值为null的情况,避免空引用异常

修改后的代码

控制器代码

public async Task<ActionResult<Users>> get_attibutes(string userName)
{
    var users = await _userManager.FindByNameAsync(userName);
    
    GetAttribute(users); // 传入查询到的用户实例,而非typeof(Users)
    
    return Ok(); 
} 

GetAttribute方法(针对Users类型)

public static void GetAttribute(Users userInstance)
{
    if (userInstance == null)
    {
        Console.WriteLine("用户实例为空");
        return;
    }
    
    PropertyInfo[] propertiesInfo = userInstance.GetType().GetProperties();
    foreach (PropertyInfo propertyInfo in propertiesInfo)
    {
        string propery_name = propertyInfo.Name;
        string property_type = propertyInfo.PropertyType.Name;
        // 获取实例的属性值,处理null情况
        object property_value = propertyInfo.GetValue(userInstance);
        string valueStr = property_value?.ToString() ?? "null";

        Console.WriteLine($"Property_Name : {propery_name}");
        Console.WriteLine($"Property_value: {valueStr}");
        Console.WriteLine($"Property_type : {property_type}\n");
    }
} 

通用版方法(支持任意实体类)

如果需要让方法适配更多实体类型,可以把参数改为object:

public static void GetAttribute(object instance)
{
    if (instance == null)
    {
        Console.WriteLine("实例为空");
        return;
    }
    
    Type t = instance.GetType();
    PropertyInfo[] propertiesInfo = t.GetProperties();
    foreach (PropertyInfo propertyInfo in propertiesInfo)
    {
        string propery_name = propertyInfo.Name;
        string property_type = propertyInfo.PropertyType.Name;
        object property_value = propertyInfo.GetValue(instance);
        string valueStr = property_value?.ToString() ?? "null";

        Console.WriteLine($"Property_Name : {propery_name}");
        Console.WriteLine($"Property_value: {valueStr}");
        Console.WriteLine($"Property_type : {property_type}\n");
    }
} 

内容的提问来源于stack exchange,提问作者Nurat Jahan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:26:05