c# - 在 aws eb 上存储 asp.net core 2 的连接字符串

标签 c# amazon-web-services asp.net-core .net-core asp.net-core-mvc

我在 aws eb 上部署了 .net core 2 应用程序。我需要暂存、质量检查和生产服务器,但不知道如何处理连接字符串? 是否可以将其存储在 eb 上的环境变量中? 或者是否可以为这三个实例创建环境并为每个实例创建不同的 application.json 文件?

最佳答案

您可以使用 Options pattern in ASP.NET Core

例如你有这样的 appsetting.json

"WebAppUrl": {
  "Staging": "someurl",
  "Qa": "someurl",
  "Prod": "someurl"
}

我需要像这样定义一个模型类来存储信息

public class WebAppUrl
{
  public string Staging { get; set; }
  public string Qa { get; set; }
  public string Prod { get; set; }
}

所以我们有了配置结构。我们需要做的最后一件事是在 Startup.cs 中注册

services.Configure(configuration.GetSection("WebAppUrl"));

所以你可以这样使用

private readonly IOptions<WebAppUrl> _webAppUrl;

public EmailSender(IOptions<WebAppUrl> _webAppUrl)
{
  _webAppUrl = _webAppUrl;
}

_webAppUrl.Value.Staging;
_webAppUrl.Value.Qa;
_webAppUrl.Value.Prod;

好的,这就是 Microsoft 设置多个 appsetting.json 的方式 file .你可以看看,因为它有点长帖子

下面是我如何根据环境使用json文件进行配置

public Startup(
            IConfiguration configuration,
            IHostingEnvironment hostingEnvironment)
        {
            _configuration = configuration;
            _hostingEnvironment = hostingEnvironment;

            var builder = new ConfigurationBuilder();

            if (_hostingEnvironment.IsDevelopment())
            {
                builder.AddUserSecrets<Startup>();
            }
            else
            {
                builder
                    .SetBasePath(hostingEnvironment.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();
            }
        }

关于c# - 在 aws eb 上存储 asp.net core 2 的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57510390/

相关文章:

c# - 如何用.cs文件替换DLL文件?

c# - C# 中的事件驱动标准输入

mysql - 从 Amazon S3 存储桶文件创建/更新 Amazon Athena 表

c# - 在哪里验证输入参数以防止 C# Web API Controller 、服务或存储库中的 SQL 注入(inject)?

c# - 如何在 C# 中将 System.Collection.IEnumerable 转换为 List<T>?

c# - Enum.GetName() As Constant 属性

asp.net-core - 找不到与命令 "dotnet-watch"匹配的可执行文件

asp.net-core - 将.Net Core应用发布到Azure之后,通过VS Online发布“运行时”文件夹

amazon-web-services - 在我的 EC2 实例上安装 SSM 代理,以便在没有 SSH 或 key 对的情况下安装 Inspector 代理

sql - 我如何获得 7 天前的日期?