programing

값은 null일 수 없습니다.파라미터 이름: connectionString appsettings.json in starter

lastcode 2023. 2. 9. 21:56
반응형

값은 null일 수 없습니다.파라미터 이름: connectionString appsettings.json in starter

접속 문자열을 appsettings.json 파일에 쓰고 스타트업 파일로 가져오려고 하는데 값이 계속 null일 수 없습니다.파라미터 이름: connectionString.여러 가지 예를 사용하고 있습니다만, ASP에서는 이 새로운 설정을 볼 수 없는 것 같습니다.NET 1.0 코어 스타트업 클래스

Appsetting.json 파일:

{
"Data": {
"DefaultConnection": {
  "ConnectionString": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"

},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}
}
}

Startup.cs을 시도하는 방법

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

 public void ConfigureServices(IServiceCollection services)
    {
        var connStr = Configuration.GetConnectionString("DefaultConnection");
        System.Console.WriteLine(connStr);
        services.AddDbContext<DbContext>(options => options.UseSqlServer(connStr)); //error right here -- Null value
}

일단은

 "Data": {
"ConnectionStrings": {
  "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},
}

"Asp"를 추가할 때 나타나는 구조와는 약간 다릅니다.NET Configuration File"을 참조하십시오.그렇게 할 때 당신은 얻을 수 있다.

"ConnectionStrings": {
  "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},

"Data" JavaScript 오브젝트가 없습니다.그래서 확장 방식이 작동하지 않는 거예요.이 구조를 기대하고 있습니다.이 구조체('데이터'가 있는 구조체)를 사용하여 다음과 같이 연결 문자열을 가져올 수 있습니다.

var connectionString = Configuration["Data:ConnectionStrings:DefaultConnection"];

에 주의해 .:. 크로스 의 사용에 몇개의 문제 .

"데이터"를 편집하는 경우:{} 이 작업을 수행할 수 있습니다.

var connectionString = Configuration["ConnectionStrings:DefaultConnection"];

이것으로 확장 방법이 동작합니다.Microsoft 확장 기능에서는, 상기의 코드와 같습니다.

var config2 = Configuration.GetConnectionString("DefaultConnection");

' 뒤에 's요.ConnectionString(appsettings.json 사용 시)Configuration.GetConnectionString("name")

여기에 이미지 설명 입력

복사하는 경우

"ConnectionStrings ": {
  "SpyStore": "Server=(localdb)\\mssqllocaldb;Database=SpyStore;Trusted_Connection=True;MultipleActiveResultSets=true;"
}

★★★★★★★★★★★GetConnectionString나는 혼란스러웠다, 나는 그것을 맴돌았고 오 기다려라 그것은 찾고 있었다.ConnectionStringsConnectionString 대신 속성 이름

DefaultConnection이며 json의 입니다.Data★★★★★★ 。

따라서 컨피규레이션파일을 정확하게 하려면

var connStr = Configuration.GetSection("Data")
                           .GetSection("DefaultConnection")["ConnectionString"];

된 예요.\했던 그에서.\\따라서 localdb 연결 문자열로 인해 다음과 같은 로드 오류가 발생했습니다.

"DefaultConnection": "Server=(localdb)\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"

다음과 같이 수정했습니다.

"DefaultConnection": "Server=(localdb)\\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"

이것이 나에게 나타난 메시지였다.

값은 null일 수 없습니다.파라미터 이름: connectionString

스타트업에서 이 라인을 변경해서 수정했습니다.

services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(
Configuration["Data:BookStoreContext:ConnectionString"]));

로.

services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("BookStoreContext")));

저도 비슷한 오류가 있었습니다.파일의 속성이 [Copy to Output Directory]-> [ Do not Copy ]이기 때문에 [appsettings . json ]파일이 로드되지 않았습니다.복사항상 저장 후 재구축으로 설정했습니다.됐다.

asp.net 코어에서는 startUp contractor 메서드에 IConfiguration을 추가하고 이 파라미터를 클래스 내 IConfiguration에서 상속된 속성에 할당해야 합니다.

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }
    public IConfiguration Configuration { get; }

오타를 고치면 문제가 해결된다.

이 문제는 asp.net core 3.0을 사용하여 발생하였습니다.해결 방법은 다음과 같습니다.

대신:

var connectionString = 구성 ["ConnectionStrings:디폴트 접속"];

사용방법:

var connectionString = 구성 ["ConnectionStrings:: Default Connection"];

여기서 강조되는 것은 연결 설정에서 이중 콜론입니다.

또 다른 실수는 ConnectionString 대신 ConnectionString을 사용했다는 것입니다(마지막 's' 참고).

다음과 같이 시도해 볼 수 있습니다.

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer("DefaultConnection")
);

이렇게 해 주세요.appsettings.json하다

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

그런 다음 콘솔을 통해 마이그레이션을 추가하면 성공합니다.

Postgres SQL을 사용하는 동안 앱 설정.Development.json은 다음을 포함해야 합니다.

"ConnectionStrings": {  
      "DefaultConnection": "User ID=user;Password=xxxx;Host=127.0.0.1;Port=5432;Database=abc;Pooling=true"
    }  

Startup.cs 파일의 내용은 다음과 같습니다.

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>
        (p => p.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));            
    }

을 에 appsetting.jsonfile > > > > > > > > > 。

"ConnectionStrings":{
   "DefaultConnection":"Server=localdb)\\MSSQLLocalDB;Datbase=MyShop;Trusted_Connection=true"
}
  • 알겠습니다. 앱 설정에서 접속 문자열의 이름이 Startup에서 설정한 것과 다르기 때문입니다.

  • 시작 시 올바른 연결 문자열 구성 코드

// replace NAMEHERE with the name of the class that inherits from DbContext
services.AddDbContextPool <NAMEHERE> (opts => opts.UseSqlServer(Configuration.GetConnectionString("here put the same Connection string name that in appsettings")));

늘 접속 문자열 문제로 너무 오랫동안 싸웠는데 이렇게 하고 있는 것을 알게 되었습니다.

builder.Services.AddDbContext<MlDataContext>(provider => new MlDataContext(config.GetConnectionString("ConnectionStrings:SqlConnectionString")));

다 요.ConnectionStrings: AND "AND"GetConnectionString 다음과 같이 했습니다. 이치노

builder.Services.AddDbContext<MlDataContext>(options => options.UseSqlServer(config.GetConnectionString("SqlConnectionString")));

Postgre DB의 경우 아래가 저를 위해 일했습니다.

    private readonly IConfiguration _config;

    string connectionString;
    public DataBaseContext(IConfiguration config)
    {
        _config = config;
        connectionString= _config.GetValue<string>("ConnectionStrings:sampleConnection");
    }

구성 파일:

"ConnectionStrings": {"sampleConnection":".." }

시작 파일: 서비스.Add Scoped();

제 경우 스타트업 클래스에 2개의 IConfiguration 정의가 있었습니다.도움이 되지 않는다:)

us가 Asp에 있던 날 이 오류가 발생했습니다.넷 코어 5나는 위의 모든 해결책을 시도해 보았지만 만족하지 못했다.그런 다음 appsettings.json 파일의 "ConnectionStrings" 섹션을 삭제하고 마이그레이션을 시작했습니다.오류가 발생한 후 섹션을 다시 작성하고 마이그레이션을 다시 시작했습니다.모두 잘 작동했다.

app.json에 정의된 모든 연결 문자열이 있는지 확인하십시오.문제는 서비스 구성에 dbContext를 추가한 두 개의 다른 프로젝트가 있다는 것입니다.

  1. identityDb를 참조한 ID 프로젝트
  2. 모든 데이터가 로직에 액세스하는 지속성 프로젝트

app.json에서 두 연결 문자열을 정의하여 문제를 해결했습니다.

시험해 보세요.버전 3.0.0에서 사용할 수 있습니다.

public class Startup { private readonly IConfigure configuration ;public startup(ICONfigure 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.AddControllersWithViews();
        services.AddDbContext<DataContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("MyPortfolio"));
        });
    }

appsettings.json

{

"로그": { "로그 레벨": { "기본값": "정보", "Microsoft": "경고", "Microsoft".호스팅.수명": "정보" } , "허용됨"호스트": "*", "ConnectionStrings": {"MyPortolio": "데이터 소스=(localdbd)"\MSSQLlocalDB, 초기 카탈로그=MyPortolioDB, 통합 보안=true}}

저도 같은 문제가 있었고, 이것으로 해결되었습니다.

connStr = Configuration.GetConnectionString("DefaultConnection");

변경처:

connStr = Configuration["DefaultConnection:ConnectionString"]

같은 에러가 발생하고 있습니다만, 오타임을 알 수 있습니다.

"ConnectionStringd": {
    "DefaultConnection":  "Server=localhost;Database=BookListRazor;Trusted_Connection=True;MutipleActiveResultSets=True"
},

올바른 입력은

"ConnectionStrings": {
    "DefaultConnection":  "Server=localhost;Database=BookListRazor;Trusted_Connection=True;MutipleActiveResultSets=True"
},

YourProjectName.csproj 파일에서 다음 행을 삭제합니다.

<Nullable>enable</Nullable>

이 경우는, 새로운 서버에의 새로운 전개입니다.환경변수 ASPNETCORE_ENVironment가 설정되어 있지 않은 것으로 나타났습니다.그래서NET Core가 앱 설정에서 연결 문자열을 가져올 수 없습니다.PROD 파일이므로 옵션에 null을 전달합니다.UseSqlServer(연결).

새로운 환경변수 ASPNETCORE_ENVironment를 만들고 그 값을 PROD로 설정하면 문제가 해결됩니다.

아래에 제시된 방법을 사용하는 대신

builder.Services.AddDbContext<FullstackAPIcontext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("FullStackConnectionString")));

연결 문자열은 Usesqlserver 뒤에 직접 추가할 수 있습니다.코드 스니펫은 다음과 같습니다.

builder.Services.AddDbContext<FullstackAPIcontext>(options =>
       {
           options.UseSqlServer("Server=myserver;Database=FullstackDb;Trusted_Connection=SSPI;Encrypt=false;TrustServerCertificate=true");
       });

변경하셔야 합니다.appsetting.json대상:

    {
  "Data": {
    "ConnectionStrings": {
      "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"

    },
    "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  }
}

이제 작동하게 됩니다.

  var connStr = Configuration.GetConnectionString("DefaultConnection");

언급URL : https://stackoverflow.com/questions/40874640/value-cannot-be-null-parameter-name-connectionstring-appsettings-json-in-start

반응형