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

VS2022下.NET Framework4.8新项目调用AWS Secrets Manager配置文件识别失败求助

问题描述

已在c:\users\{name}\.aws目录下配置好AWS的config和credentials文件,使用Visual Studio 2022开发.NET Framework 4.8项目时,旧解决方案能通过以下代码正常调用AWS Secrets Manager的GetSecretValue方法获取密钥:

using (var client = new AmazonSecretsManagerClient(RegionEndpoint.USEast1))
{
    GetSecretValueRequest request = new GetSecretValueRequest();
    request.SecretId = name;
    request.VersionStage = "AWSCURRENT";
    var result = client.GetSecretValue(request);
    return JsonConvert.DeserializeObject<MyCustomObject>(result.SecretString);
}

但新创建的同版本解决方案无法识别本地配置文件,持续报错:Unable to get IAM Security Credentials from EC2 Instance MetaData Service

解决方案
  • 对齐AWS SDK版本:确保新解决方案引用的AWSSDK.SecretsManager及相关AWS SDK包版本与旧项目完全一致,版本差异可能导致凭证加载逻辑变更。
  • 显式指定本地凭证加载:初始化客户端时手动指定使用本地存储的配置文件凭证,跳过EC2元数据服务的自动检测:
    var credentials = new StoredProfileAWSCredentials();
    using (var client = new AmazonSecretsManagerClient(credentials, RegionEndpoint.USEast1))
    {
        GetSecretValueRequest request = new GetSecretValueRequest();
        request.SecretId = name;
        request.VersionStage = "AWSCURRENT";
        var result = client.GetSecretValue(request);
        return JsonConvert.DeserializeObject<MyCustomObject>(result.SecretString);
    }
    
  • 检查Visual Studio凭证配置:打开Visual Studio的「AWS Explorer」,确认已选中正确的本地AWS配置文件,新项目可能默认优先使用EC2实例角色等其他凭证源。
  • 配置App.config明确凭证源:在新项目的App.config中添加配置项,强制指定使用本地配置文件:
    <appSettings>
      <add key="AWS_PROFILE" value="default"/>
      <add key="AWS_CONFIG_FILE" value="C:\Users\{name}\.aws\config"/>
    </appSettings>
    
  • 清理项目缓存:删除新项目的bin和obj目录,重新生成项目,避免缓存的无效配置干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:53:28