如何使用ABP阅读UserSecrets?

时间:2018-03-27 00:57:19

标签: c# configuration aspnetboilerplate

我可以看到秘密被推入某种存储配置,但我不明白如何访问变量。 在配置构建期间,我可以看到它读取了我的应用程序密码,但稍后当我将IConfiguration注入App Service时,密钥就不存在了。

这是我到目前为止所做的:

public class EmailAppService : MyAppServiceBase, IEmailAppService
{
    private IConfiguration _configuration { get; }

    public EmailAppService(IConfiguration Configuration)
    {
        _configuration = Configuration;
    }

    /// <summary>
    /// Signup just involved sending an email to Rhyse at the moment.
    /// </summary>
    /// <param name="input">Users email</param>
    [AbpAllowAnonymous]
    public async Task<Response> SignupToBetaAsync(SignUpToBetaInput input)
    {
        // from https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/csharp.html
        var apiKey = _appConfiguration["SENDGRID_API_KEY"];
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("test@example.com", "Example User");
        var subject = "Sending with SendGrid is Fun";
        var to = new EmailAddress("fakeemail@gmail.com", "Example User");
        var plainTextContent = "and easy to do anywhere, even with C#";
        var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        return await client.SendEmailAsync(msg);
    }

有关如何执行此操作的一些文档会很好。

2 个答案:

答案 0 :(得分:1)

注入IConfiguration不会让您了解用户的秘密。

使用静态方法AppConfigurations.Get并指定addUserSecrets: true代替:

public class EmailAppService : MyAppServiceBase, IEmailAppService
{
    private readonly IConfigurationRoot _appConfiguration;

    public EmailAppService()
    {
        _appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder(), addUserSecrets: true);
    }

    // ...
}

在Web项目中,您可以注入IHostingEnvironment并使用扩展方法:

_appConfiguration = env.GetAppConfiguration();

答案 1 :(得分:0)

最终对我有用的方法是使用此指南: https://www.twilio.com/blog/2018/05/user-secrets-in-a-net-core-web-app.html

secrets.json示例:

{
  "Authentication": {
    "Google": {
      "ClientId": "baerbaeb.apps.googleusercontent.com",
      "ClientSecret": "bahababbtY8OO"
    },
    "Microsoft": {
      "ApplicationId": "barberbaerbaerbaerb",
      "Password": "aerbaerbaerbaerbaerb"
    }
  },
  "Sendgrid": {
    "ApiKey": "aerbaerbaerbearbearbaerbeabeabr"
  }
}

Azure应用程序设置的格式如下:

Authentication:Google:ClientId
Sendgrid:ApiKey

添加一些配置类。

public class GoogleApiConfig
{
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
}

然后像这样注册它们:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.Configure<GoogleApiConfig>_appConfiguration.GetSection("Authentication:Google"));
    services.Configure<MicrosoftApiConfig>_appConfiguration.GetSection("Authentication:Microsoft"));
  services.Configure<SendgridApiConfig>_appConfiguration.GetSection("Sendgrid"));

然后只需注入IOptions<MicrosoftApiConfig>即可正常使用-简单而强大!