我已经用过:
user-secret set "AWSAccessKey""my access key"
和
user-secret set ""AWSSecretKey""my secret key"
让我的 key 进入 secret 商店。
我有这个类,我将使用它通过 Amazon SES 发送电子邮件,但我不知道如何将我的 key 放入其中。
public class MailHelper
{
public void SendEmailSes(string senderAddress, string receiverAddress, string subject, string body)
{
using (var client = new AmazonSimpleEmailServiceClient(
new BasicAWSCredentials("[AWSAccessKey]", "[AWSSecretKey]"),
RegionEndpoint.USEast1))
{
var sendRequest = new SendEmailRequest
{
Source = senderAddress,
Destination = new Destination { ToAddresses = new List<string> { receiverAddress } },
Message = new Message
{
Subject = new Content(subject),
Body = new Body { Text = new Content(body) }
}
};
var response = client.SendEmail(sendRequest);
}
}
}
为了让这些 key 在我的 MailHelper 类中可用,我应该在我的 Startup.cs 中放些什么? MailHelper 类本身需要添加什么?
我看过一些 MVC Controller 的示例,但我找不到任何尚未实现某些预期接口(interface)的自定义实用程序类。
最佳答案
您的设置类:
public class AwsSettings
{
public string AccessKey { get; set; } = string.Empty;
public string AccessSecret{ get; set; } = string.Empty;
}
如果你的设置在 config.json 中,你会这样做:
{
"AwsSettings": {
"AccessKey": "yourkey",
"AccessSecret": "yoursecret"
}
}
在 Startup 中你需要这个:
services.Configure<AwsSettings>(Configuration.GetSection("AwsSettings"));
您的邮件程序类需要将设置注入(inject)到构造函数中
using Microsoft.Framework.OptionsModel;
public class MailHelper
{
public MailHelper(IOptions<AwsSettings> awsOptionsAccessor)
{
awsSettings = awsOptionsAccessor.Options;
}
private AwsSettings awsSettings;
... your other methods
}
UserSecrets 只是另一个配置源,因此您可以将设置放在那里而不是 config.json,但您需要模拟结构以便它可以映射到您的类,因此您可以像这样用冒号设置它们:
user-secret set "AwsSettings:AccessKey" "my access key" and
user-secret set "AwsSettings:AccessSecret" "my secret key"
这等同于我为 config.json 展示的结构
现在将从用户 secret 中加载设置并注入(inject)您的邮件
关于c# - 如何将 ASP.NET 5 (vNext) 用户 secret 注入(inject)我自己的实用程序类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599573/