programing

asp.net core 2.0 - 값은 null일 수 없습니다.매개 변수 이름: connectionString

padding 2023. 8. 11. 21:33
반응형

asp.net core 2.0 - 값은 null일 수 없습니다.매개 변수 이름: connectionString

마이그레이션 추가 시 패키지 관리자 콘솔에서 다음 오류가 발생했습니다.

값은 null일 수 없습니다.매개 변수 이름: connectionString

여기가 제 스타트업입니다.

namespace MyProject
{
    public class Startup
    {
        public IConfiguration Configuration { get; set; }
        public Startup(IConfiguration config)
        {
            Configuration = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(options =>
                             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient<IDevRepo, DevRepo>();
            services.AddMvc();
            services.AddMemoryCache();
            services.AddSession();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(Configuration["Message"]);
            });
        }
    }
}

프로그램 클래스:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("appsettings.json")
                       .Build())

            .UseStartup<Startup>()
            .Build();
}

appsettings.json:

{
  "Message": "Hello World",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

흥미롭게도 앱을 실행하면 "Hello World"라고 표시되지만 마이그레이션을 추가할 때 connectionString을 찾을 수 없습니다.누가 여기 불 좀 켜 주시겠어요?감사해요.

연결 문자열을 찾을 수 없을 때 이 문제가 발생했습니다.

시작 클래스에 다음 코드가 있을 수 있습니다.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BenchmarkContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("yourConnectionString name from appsettings.json")));
    }

다음 방법으로 문제를 해결할 수 있습니다.

- 1 대신 - 신대Configuration.GetConnectionString("yourConnectionString name from appsettings.json(in develop mode: 'appsettings.Development.json')")그냥 연결 끈을 놓으세요.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BenchmarkContext>(options =>
  options.UseSqlServer("Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"));
    }

2 - 구성 파일을 사용하려는 경우 다음 코드를 시작 클래스에 추가합니다.

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
public IConfiguration Configuration;

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BenchmarkContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
    }

Appsettings.json 파일(개발 모드: 'appsettings')입니다.Development.json':

{
  "ConnectionStrings": {
    "TestConnection": "Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"
  }
}

그런 다음 Package Manager 콘솔에서 'add-migration name' 명령을 실행합니다.

저도 같은 문제가 있었지만, 제 해결책은 훨씬 더 간단했습니다.제가 한 일은 다음에서 appsettings.json의 순서를 변경한 것뿐입니다.

{
  "Message": "Hello World",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

대상:

{
   "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Message": "Hello World"
}

appsettings.json 파일에 파라미터 시퀀스/순서가 있는 것이 의심됩니다.

서비스를 로드 테스트할 때 이러한 문제가 있었고(모두에게 권장) 오류가 있는 요청이 최대 3/1000개 있어 변경했습니다.

services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

로.

string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(connectionString));

따라서 연결 문자열을 한 번 읽고 모든 요청에 대해 구성을 사용하지 않습니다.이제 100% 요청이 성공했습니다.하지만 그것은 안에 있는 벌레인 것 같습니다.넷코어

저는 제 문제를 발견했습니다.

IDesignTimeDbContextFactory를 상속하는 AppDbContextFactory 클래스가 있습니다.이 클래스를 삭제하면 이 문제가 해결됩니다.

저도 같은 문제가 있었습니다. 왜냐하면 저는 Startup.cs 의 기본값을 사용했기 때문입니다.구성 속성을 편집했습니다.

public IConfiguration Configuration { get; }

대상:

public IConfiguration Configuration;

그리고 그게 효과가 있었어!만약 누군가가 왜 그런지 말한다면 감사할 것입니다.

저는 다음과 같은 이유로 비슷한 문제를 겪었습니다.

  • appsettings.json이 프로젝트에 포함되지 않았습니다.
  • appsettings.json이 포함되지 않은 경로에서 프로젝트를 실행하고 있었습니다.

저도 같은 오류가 발생하여 "ConnectionStrings"를 appsettings.json 파일의 첫 번째 변수로 이동하여 해결했습니다.

csproj 파일의 DotNetCliToolReference에 문제가 있을 수 있습니다.이전 버전의 asp.net core에서 프로젝트를 마이그레이션하는 경우 DotNetCliToolReference는 자동으로 업데이트되지 않습니다.아래 스니펫에 표시된 대로 CLI 2.0.0 버전을 사용하도록 project.csproj 파일을 업데이트합니다.

<ItemGroup>

        ...
          <DotNetCliToolReference 
               Include="Microsoft.EntityFrameworkCore.Tools.DotNet" 
               Version="2.0.0" />
</ItemGroup>

프로젝트 폴더에서 -v 스위치를 사용하여 dotnet 명령을 다시 실행하여 결과를 확인합니다.

dotnet ef database update -v

또한 Microsoft를 다시 확인합니다.2.0.0 버전을 참조하는 EntityFrameworkCore 너겟 패키지입니다.이전 EF 패키지를 제거하거나 업데이트합니다.최소는 다음과 같습니다.

  • 마이크로소프트.엔티티 프레임워크 코어입니다.Sql서버

  • 마이크로소프트.엔티티 프레임워크 코어입니다.설계.

이 시점에서 둘 다 2.0.0.

동일한 문제가 발생했으며 연결 이름이 일치하는지 확인해야 했습니다.

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

다음 중 ****연결 문자열:Default Connection***은(는) 모든 문제가 발생한 곳입니다.Startup.cs 및 appsettings.json(appsettings)에서 동일한 설정인지 확인합니다.2019년 Vs.json의 개발.json

제가 이것을 고친 후에, 모든 것이 잘 되었습니다.

저도 비슷한 문제가 있었습니다.는 에 오타가 .appsettings.json 중입니다.ConnectionsStringsConnectionStrings날 위해 해줬어요!

저는 올바른 기본 경로를 설정하여 문제를 해결했습니다.문제는 마이그레이션이나 다른 패키지의 다른 모든 항목이 appsetting.json 파일에 대한 잘못된 경로를 사용한다는 것입니다.공식적인 문제인지는 잘 모르겠습니다.

저는 방금 제 Startup.cs 을 다음과 같이 변경했습니다.

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

그런 다음 appsettings.json이 없으면 올바른 위치에 복사하기만 하면 됩니다.

이것은 저에게 완벽하게 효과가 있었습니다.

public IConfiguration Configuration;
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext.ApplicationDbContext>(options => 
            //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            options.UseSqlServer("Server=serverAddress; Database=dbName; user=username; password=pswd"));
}

주석이 달린 부품은 대체할 위치를 참조하는 것과 같습니다.

다른 시나리오에서는 구성을 설정할 수 있습니다.appsettings.json에서 appsettings 대신 연결 문자열을 설정합니다.개발.json

"를 지정할 때도 비슷한 문제가 있었습니다.현재 프로세스 경로로 "ContentRoot"를 사용합니다.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:3001")
            .UseStartup<Startup>()
            .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));

따라서 Add-Migration을 실행할 때 프로세스 경로가 프로젝트 bin 경로와 다르므로 프로세스가 appsettings.json 파일을 찾을 수 없습니다."을(를) 제거했을 때.UseContentRoot" 행을 마이그레이션했습니다.

나는 멍청하고 오타가 있었습니다.

{
  "Conn'ce'tionStrings": {
    "DefaultConnection": "Data source=datingapp.db"
  },

로 바꿨습니다.

{
  "ConnectionStrings": {
    "DefaultConnection": "Data source=datingapp.db"
  },

새로 만든 프로젝트를 ASP에 사용하려다가 비슷한 문제가 생겼습니다.NET Core 2.0 Web API.제가 파악한 문제의 원인은 개발 환경에 지정된 애플리케이션 설정이 추가되지 않은 것입니다.시작 파일을 다음으로 업데이트하여 수정했습니다.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    this.Configuration = builder.Build();
}

이 경우 프로그램 클래스는 다음과 같습니다.

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

제 문제는 netcoreapp2.1 폴더에서 App.dll을 실행하려고 할 때였는데, 올바른 폴더는 netcoreapp2입니다.1\sigma\

이전에 appsettings 파일에서 연결 문자열의 이름을 변경한 적이 있고 프로젝트에 연결 문자열이 있는 경우 DesignTimeDbContextFactory 클래스에서 이름 변경을 생략했으며 Entity 프레임워크에서 확인한 경우 이 문제에서 실행할 수 있습니다.

IDesignTimeDbContextFactory를 사용하는 경우 매개 변수가 없는 기본 생성자를 해당 생성자에 추가해야 합니다.다음과 같은 방법을 사용해 보십시오.

public DbContextFactory()
{
    IConfigurationRoot configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json", false, true)
        .Build();

    _connectionString = configuration.GetConnectionString("ConnectionStringName");
}

나에게 그것은 내가 가지고 있던 것이었습니다.appSettings.json대신에appsettings.json어떤 이유에서인지(VS가 새로 생성된 프로젝트에서 이 작업을 수행했는지 또는 내가 이 작업으로 이름을 변경했는지는 확실하지 않습니다.)일단 이름을 바꾸고 나면 잘 작동했습니다.

저는 저를 위해 그것이 무엇인지 덧붙이자고 생각했습니다.저는 인기 있는 튜토리얼을 따라 appsettings.json 및 종속성 주입을 콘솔 애플리케이션에 추가했습니다.설정에서 현재 디렉터리를 참조하고 구성 작성기의 기본 경로를 설정하는 데 사용하고 있는지 몰랐습니다.로컬에서 실행할 때는 잘 작동했지만, SQL 예약 작업을 배포하고 실행하려고 하자마자 DLL이 있는 디렉터리가 아니라 명령이 입력되는 디렉터리를 가져갔기 때문에 appsettings.json 파일을 찾을 수 없었습니다.현재 디렉터리를 가져오고 기본 경로로 설정하는 데 사용되는 줄만 제거하면 정상적으로 작동합니다.DLL과 동일한 폴더로 기본 설정되어 있는 것 같습니다.

저는 이 문제를 가지고 있었습니다.connectionstringappsetting.json파일, 그리고GetConnectionString(connectionstrings)의 매개 변수.startup.cs여분을 제거한 후sstartup.cs문제가 사라졌습니다.

확인 여부ASPNETCORE_ENVIRONMENT변수가 서버에 올바르게 설정되었습니다.해당 환경에 따라 필요할 수 있습니다.appsettings.json대신에appsettings.Staging.json또는appsettings.Production.json.

제 경우에는 사용했습니다.configuration["DbContext"]

 services.AddDbContext<AstroBhaskarDbContext>(option =>
 {
     option.UseSqlServer(configuration["DbContext"]);
 });

그리고 나서 나는 교체했습니다.configuration["DbContext"]로.configuration.GetConnectionString("DbContext")하기와 같이

  services.AddDbContext<AstroBhaskarDbContext>(option =>
  {
     option.UseSqlServer(configuration.GetConnectionString("DbContext"));
  });

EF nuget 패키지를 최신 버전(6.4.4)으로 업데이트하는 것 외에는 아무 것도 작동하지 않았습니다.

언급URL : https://stackoverflow.com/questions/46010003/asp-net-core-2-0-value-cannot-be-null-parameter-name-connectionstring

반응형