我有以下代码:
public void ConfigureServices(IServiceCollection services)
{
// AWS Options
var awsOptions = Configuration.GetAWSOptions();
services.AddDefaultAWSOptions(awsOptions);
var client = awsOptions.CreateServiceClient<IAmazonDynamoDB>();
var dynamoDbOptions = new DynamoDbOptions();
ConfigurationBinder.Bind(Configuration.GetSection("DynamoDbTables"), dynamoDbOptions);
services.AddScoped<IDynamoDbManager<MyModel>>(provider => new DynamoDbManager<MyModel>(client, dynamoDbOptions.MyModel));
}
public class DynamoDbManager<T> : DynamoDBContext, IDynamoDbManager<T> where T : class
{
private DynamoDBOperationConfig _config;
public DynamoDbManager(IAmazonDynamoDB client, string tableName) : base(client)
{
_config = new DynamoDBOperationConfig()
{
OverrideTableName = tableName
};
}
}
我的 Appsettings.json 如下:
{
"AWS": {
"Region": "us-east-1",
"AwsId": "xxx",
"AwsPassword": "xxx"
},
"DynamoDbTables": {
"MyModel": "MyTable"
}
}
当我运行代码时,出现错误:
AmazonServiceException: Unable to find credentials
异常 1(共 3 个): Amazon.Runtime.AmazonClientException:无法在 CredentialProfileStoreChain 中找到“默认”配置文件。在 E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials\FallbackCredentialsFactory.cs 中的 Amazon.Runtime.FallbackCredentialsFactory.GetAWSCredentials(ICredentialProfileSource 源):第 72 行
异常 2(共 3 个): System.InvalidOperationException:未使用 AWS 凭证设置环境变量 AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN。
异常 3(共 3 个): System.Net.Http.HttpRequestException:发送请求时发生错误。 ---> System.Net.Http.WinHttpException:操作超时 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
我尝试了很多方法,但没有成功。
我已经尝试过:
将配置文件设置为: Amazon.Runtime.AmazonServiceException: Unable to find credentials
还尝试设置环境变量:
https://github.com/aws/aws-sdk-net/issues/499
但仍然无法克服这个错误。
最佳答案
因此,当我们使用AWS SDK时,我们需要设置并提供AWS访问 key 和 secret key 。据我所知,它不会直接从应用程序设置中读取。所以我发现下面是两种可以设置这些凭据的工作方法。
方法 1 - 使用凭据文件
您可以创建一个凭据文件并将您的凭据存储在其中。以下是文件的格式。
[default]
aws_access_key_id = your id goes here
aws_secret_access_key = your password goes here
在上面的文件中,“default”是您的个人资料的名称。
创建上述文件后,您需要在 Appsettings.json 文件中指定相同的内容:
"AWS": {
"Profile": "default",
"ProfilesLocation": "C:\\filelocation\\awscredentials",
"Region": "us-east-1",
}
方法 2 - 设置和读取环境变量
我们可以在startup.cs文件中设置环境变量,如下所示:
Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", Configuration["AWS:AwsId"]);
Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", Configuration["AWS:AwsPassword"]);
Environment.SetEnvironmentVariable("AWS_REGION", Configuration["AWS:Region"]);
并从我们的 appSettings.json 文件中读取这些变量:
AWS": {
"Region": "us-east-1",
"AwsId": "xxxx",
"AwsPassword": "xxxx"
}
关于c# - Net Core 2.0 AmazonServiceException : Unable to find credentials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53176420/