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

.NET自定义属性无法传入配置值?求可行解决方案

解决方案

首先明确报错原因:属性的构造函数参数必须是编译时常量,你注入的_config.configString是运行时才会赋值的变量,不符合C#对属性参数的要求,所以报错。

以下是两种可行的修改方案:

方案一:在授权过滤器中通过依赖注入获取配置

这种方式不需要给属性传参数,直接在过滤器逻辑中获取已注入的Config实例:

控制器代码修改

public MyController(ILogger<MyController> logger, Config config)
{
    _logger = logger;
    _config = config;
}

[HttpGet("/MyThings")]
[CustomAuthorize] // 移除原有的参数传递
public async Task<ActionResult> Get(long d)
{
    _logger.LogInformation("Info ...");
    try
    {
        // 你的业务逻辑代码
    }
    catch(Exception ex)
    {
        // 异常处理逻辑
    }
}

自定义授权属性修改

public class CustomAuthorize : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // 从请求服务容器中获取Config实例
        var config = context.HttpContext.RequestServices.GetService<Config>();
        if (config == null)
        {
            // 配置获取失败,返回500错误
            context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            return;
        }

        string securityString = config.configString;
        
        // 在这里执行你的安全校验逻辑
        // 示例:如果校验不通过,返回401未授权
        // if (!IsValid(securityString))
        // {
        //     context.Result = new UnauthorizedResult();
        // }
    }
}

方案二:传递配置键名,动态读取配置

如果你的配置是通过IConfiguration管理的,可以通过传递配置键的方式,在过滤器中动态读取对应值:

自定义授权属性修改

public class CustomAuthorize : Attribute, IAuthorizationFilter
{
    private readonly string _configKey;

    // 构造函数接收配置键名(常量字符串,符合属性参数要求)
    public CustomAuthorize(string configKey)
    {
        _configKey = configKey;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();
        if (configuration == null)
        {
            context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            return;
        }

        // 根据键名读取配置值
        string securityString = configuration[_configKey];
        
        // 执行安全校验逻辑
        if (string.IsNullOrEmpty(securityString) || !IsValid(securityString))
        {
            context.Result = new UnauthorizedResult();
        }
    }

    // 示例校验方法
    private bool IsValid(string securityString)
    {
        // 你的校验逻辑
        return true;
    }
}

控制器代码修改

[HttpGet("/MyThings")]
// 传递配置文件中的键路径,比如appsettings.json里的"Config:ConfigString"
[CustomAuthorize("Config:ConfigString")]
public async Task<ActionResult> Get(long d)
{
    _logger.LogInformation("Info ...");
    try
    {
        // 你的业务逻辑代码
    }
    catch(Exception ex)
    {
        // 异常处理逻辑
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:05:19