是否可以使用反射为 ModelStateDictionary 添加模型错误?

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

我有一个在编译时不知道的控制器。所以我需要使用反射来添加 modelError。这可能吗?或者还有其他方法可以做到吗?

我认为它可能会起作用(但事实并非如此)。

var modelProperty = controller.GetType().GetProperty("ModelState");
var addErrorMethod = typeof(ModelStateDictionary).GetMethod("AddModelError", new[] { typeof(string), typeof(string) });
addErrorMethod.Invoke(modelProperty, new object [] { "key", "message" });

我得到的错误:对象与目标类型不匹配。

c# asp.net-mvc asp.net-core reflection
1个回答
0
投票

已解决:已添加

var modelValue = (ModelStateDictionary)modelProperty.GetValue(controller);
        
addErrorMethod.Invoke(modelValue, new object [] { "key", "message" });

在我的第一次尝试中,modelProperty只是一个RuntimePropertyInfo。我忘记从我的控制器获取 modelState 实例。

© www.soinside.com 2019 - 2024. All rights reserved.