且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net核心通过ENV变量覆盖连接字符串

更新时间:2023-02-17 08:20:26

对于-e,它将覆盖系统环境,该环境将在您从代码检索时更改连接字符串,不会影响appsettings.json中的内容.

For -e, it will override the system environment which will change the connectionstring when you retrive from code, it will not affect the content in appsettings.json.

例如

  1. 假设您有一个appsettings.json

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestDockerConfiguration-416C6FD2-3531-42D6-9EDE-18AC45901208;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
        "LogLevel": {
        "Default": "Warning"
        }
    },
    "AllowedHosts": "*"
}

  • 通过

  • Retrive the connectionstring by _configuration.GetConnectionString("DefaultConnection") like

    public class HomeController : Controller
    {
        private readonly IConfiguration _configuration;
        public HomeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public IActionResult Index()
        {
            return Ok(_configuration.GetConnectionString("DefaultConnection"));
            //return View();
        }
    }
    

  • 对于docker run -it -p 8888:80 dockerconfiguration,它将为索引操作返回"Server=(localdb)\\mssqllocaldb;Database=aspnet-TestDockerConfiguration-416C6FD2-3531-42D6-9EDE-18AC45901208;Trusted_Connection=True;MultipleActiveResultSets=true"

  • For docker run -it -p 8888:80 dockerconfiguration, it will return "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestDockerConfiguration-416C6FD2-3531-42D6-9EDE-18AC45901208;Trusted_Connection=True;MultipleActiveResultSets=true" for Index Action

    对于docker run -it -p 8888:80 dockerconfiguration -e "ConnectionStrings:DefaultConnection"="testsqlstring",它将返回testsqlstring

    因此,如果您只想在运行时覆盖appsettings.json中的值,则只需指定类似步骤4

    So, if you only want to override the value in appsettings.json during runtime, you just need to specify like Step 4

    如果您希望更改docker容器中的appsettings.json文件,可以按照以下步骤

    If you prefer change the appsettings.json file in docker container, you could follow steps below

    1. 使用apt-get install vim -y
    2. 安装vi命令
    3. 运行docker exec -it 43ea835776dd /bin/bash进入容器
    4. 运行ls列出文件并找到appsettings.json
    5. 运行vi appsettings.json修改内容
    6. 运行cat appsettings.json检查内容是否已更改
    7. 运行exit并访问Home/Index以检查结果.
    1. Install vi command with apt-get install vim -y
    2. Run docker exec -it 43ea835776dd /bin/bash to go into container
    3. Run ls to list files and find the appsettings.json
    4. Run vi appsettings.json to modify the content
    5. Run cat appsettings.json to check the content whether it is changed
    6. Run exit and access the Home/Index to check the result.