ASP.NET MVC如何动态填充或修改Attribute的属性值
首先明确前提:.NET 中 Attribute 属于编译时静态元数据,本身的设计不支持运行时直接修改属性值,你要实现的动态读取配置赋值,需要调整实现逻辑,以下是两种常用的可行方案:
方案1:调整 PrivilegeAttribute 内部实现(推荐,侵入性最小)
这种方案不需要修改其他调用逻辑,仅调整 Attribute 本身的取值逻辑,让 SysCaption 运行时自动读配置:
- 修改
PrivilegeAttribute定义,新增配置键属性,把 SysCaption 改为只读属性自动读 web.config:
public class PrivilegeAttribute : Attribute { // 用于传入web.config中对应的配置键 public string SysCaptionConfigKey { get; set; } // 取值时自动读配置,无配置时返回空 public string SysCaption => System.Configuration.ConfigurationManager.AppSettings[SysCaptionConfigKey] ?? string.Empty; }
- 修改常量上的 Attribute 声明,传入对应的配置键:
[Privilege(SysCaptionConfigKey = "Course_IndexSelf_Caption")] public const string View_Course_IndexSelf = "View Course IndexSelf";
- 在 web.config 的
appSettings节点中添加对应配置:
<appSettings> <add key="Course_IndexSelf_Caption" value="你需要的动态配置值" /> </appSettings>
后续所有代码反射读取该 Attribute 的 SysCaption 属性时,会自动返回 web.config 中的配置值,不需要额外修改其他逻辑。
方案2:在反射读取 Attribute 的位置做适配(适合无法修改 Attribute 源码的场景)
如果你不能动 PrivilegeAttribute 的源码,可以在所有读取该 Attribute 的位置做兼容,优先取配置值:
// 原读取Attribute的逻辑 var fieldInfo = typeof(你的常量所在类名).GetField(nameof(View_Course_IndexSelf)); var privilegeAttr = fieldInfo.GetCustomAttribute<PrivilegeAttribute>(); // 新增逻辑:优先读web.config配置,无配置时用Attribute原有的SysCaption值 var sysCaption = System.Configuration.ConfigurationManager.AppSettings[$"{fieldInfo.Name}_SysCaption"] ?? privilegeAttr.SysCaption;
对应 web.config 配置参考:
<add key="View_Course_IndexSelf_SysCaption" value="你需要的动态配置值" />
不推荐的方案:用反射直接修改Attribute属性
虽然可以通过反射强制修改 Attribute 实例的属性值,但 Attribute 是全局共享的元数据,多线程场景下会有并发脏读问题,同时违背了 Attribute 作为编译时元数据的设计原则,容易引发不可预期的bug,不建议使用。
内容的提问来源于stack exchange,提问作者Mostafa
相关产品推荐
相关产品推荐

