c# - System.ArgumentNullException:值不能为null。 (参数 'connectionString')asp.net Core Docker-compose

标签 c# mysql docker asp.net-core docker-compose

我有一个dockerized asp.net Core应用程序试图连接到mySql数据库。两者都在docker-compose内部运行。当我在没有Docker的情况下测试到本地数据库的连接时,我的代码工作正常,但是当我将其部署在docker-compose内的Vm上并且调用了我的一个 Controller 时,出现此错误:System.ArgumentNullException:值无法为空。 (参数'connectionString')。
这是我的docker-compose:

version: '3'
services:
  dbgil:
   container_name: dbgil
   image: mysql
   restart: always
   ports:
     - 3306:3306
   environment:
     MYSQL_ROOT_PASSWORD: root
   volumes:
     - dbdata:/var/lib/mysql
  webserver:
    depends_on:
      - dbgil
    image: lionelquirynen/gillesquirynensys:latest
    ports:
      - "8021:80"
    links:
      - dbgil
volumes:
    dbdata:

这是我在asp.net核心应用程序中的启动:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GillesQuirynenSys.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace GillesQuirynenSys
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<MySqlDbContext>(options =>
                options.UseMySql("server=localhost;port=3306;database=test;user=root;password=root;convert zero datetime=True"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MySqlDbContext context)
        {
            context.Database.EnsureCreated();
            var databaseCreator = context.GetService<IRelationalDatabaseCreator>();
            databaseCreator.CreateTables();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}



我首先在我的appsettings.json文件中有连接字符串,但是却遇到了同样的错误,因此我尝试对其进行硬编码,但没有任何改变。有任何想法吗?看来我的配置工作正常(至少,它在本地没有Docker)。

PS:这是我的asp.net Core应用程序的DockerFile,然后将其推送到DockerHub:
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["GillesQuirynenSys/GillesQuirynenSys.csproj", "GillesQuirynenSys/"]
RUN dotnet restore "GillesQuirynenSys/GillesQuirynenSys.csproj"
COPY . .
WORKDIR "/src/GillesQuirynenSys"
RUN dotnet build "GillesQuirynenSys.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "GillesQuirynenSys.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "GillesQuirynenSys.dll"]

最佳答案

我很高兴我的回答有所帮助。
因此,基本上在docker容器中,MySQL db的服务器名称与docker-compose.yml文件中声明的服务名称相同。

请注意您的代码:
代替这个:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<MySqlDbContext>(options =>
                options.UseMySql("server=localhost;port=3306;database=test;user=root;password=root;convert zero datetime=True"));
        }

->您在哪里硬编码您的连接字符串

试试这个:
      public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<MySqlDbContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
        }

并调整appsettings.json文件-对于生产(docker容器)构建,您将具有:
{
  "ConnectionStrings": {
    "DefaultConnection": "server=dbgil;port=3306;database=test;user=root;password=root;convert zero datetime=True"
  }
...
}


appsettings.Development.json中,您将有一个用于Development模式的连接字符串(您的本地主机):
{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=3306;database=test;user=root;password=root;convert zero datetime=True"
  }
...
}

关于c# - System.ArgumentNullException:值不能为null。 (参数 'connectionString')asp.net Core Docker-compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61833736/

相关文章:

c# - 在 C# 中使用数组的第一步

c# - 了解 C# 编译器如何处理链接 linq 方法

c# - 我是否需要删除非托管代码中通过 Marshal.PtrToStructure 编码(marshal)的结构?

linux - Debian 11 (bullseye) 上的 "The repository does not have a Release file"错误,即使存储库有 Release 文件

docker - 如何让 docker registry 在 windows server 2016 上工作

java - Spring Cloud 与 Docker Swarm 和 Kubernetes 等编排工具的组合

c# - 检索包含 XML 的 HTTP POST 请求

Mysql更改信息schema的列排序规则和字符集

php - 如何从同一个表中选择不同的总和值

mysql - 将 mySQL 查询转换为具有多个条件的 Laravel 5