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

ASP.NET Patch接口中Convert.ChangeType转字符串到枚举抛异常的解决方法

解决枚举属性更新时的InvalidCastException问题

问题核心在于Convert.ChangeType无法直接将字符串(即使是数字格式)转换为枚举类型,需要针对枚举类型使用专用的转换逻辑。以下是具体修复方案:

一、修正核心转换逻辑

替换原代码中的类型转换部分,增加枚举类型的判断与处理:

try
{
    Type targetType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
    object? safeValue = null;

    if (propVal.Value != null)
    {
        if (targetType.IsEnum)
        {
            // 处理枚举类型,支持数字字符串或枚举名称字符串输入
            if (Enum.TryParse(targetType, propVal.Value, ignoreCase: true, out var enumValue) 
                && Enum.IsDefined(targetType, enumValue))
            {
                safeValue = enumValue;
            }
            else
            {
                return BadRequest($"{propVal.Value} 不是 {propVal.PropertyName} 的有效值");
            }
        }
        else
        {
            // 保留原有的非枚举类型转换逻辑
            safeValue = Convert.ChangeType(propVal.Value, targetType);
        }
    }

    propertyInfo.SetValue(person, safeValue);
}
catch (InvalidCastException)
{
    return BadRequest($"{propVal.Value} 无法转换为 {propVal.PropertyName} 的类型");
}

二、关键改进说明

  • 枚举专属处理:通过targetType.IsEnum识别枚举类型,使用Enum.TryParse完成转换,避免Convert.ChangeType的局限性
  • 双格式支持:同时兼容数字字符串(如"1"对应Level1)和枚举名称字符串(如"Level1")输入
  • 有效性校验:用Enum.IsDefined确保输入值是枚举中定义的合法值,防止无效值被设置
  • 无异常式判断:使用Enum.TryParse替代Enum.Parse,避免依赖异常捕获处理错误,代码更高效

三、额外必修复的笔误

原代码中存在拼写错误:

foreach (var propVal in model.ProrpertyValues)

应修正为:

foreach (var propVal in model.PropertyValues)

该错误会导致循环逻辑完全不执行,是潜在的功能失效点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:12:53