Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString') after Upgrading .NET 5 to .NET 7

huangapple go评论65阅读模式
英文:

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString') after Upgrading .NET 5 to .NET 7

问题

I have upgraded my API to be working with .NET 7 and Ubuntu 23.04, everything went fine, the API and database are connected on my local machine and I can send request, but when I publish and deploy the app to my server, it seems that it doesn't read the connectionString in appsetting.json.

Here is my appsettings.json

{
    "AppSettings": {
        "Secret": "*************",
        "EmailFrom": "********",
        "SmtpHost": "v******",
        "SmtpPort": 587,
        "SmtpUser": "a*****",
        "SmtpPass": "HJu******"
    },

    "ConnectionStrings": {
        "WebApiDatabase": "Data Source=WebApiDatabase.db",
        "HangfireConnection": "Server=**.**.***.***;Port=5432;Database=Min;User Id=postgres;Password=min***;" //server
        //"HangfireConnection": "Host=localhost;Port=5432;Database=Min;User Id=postgres;Password=*****;" // local
    },

    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information",
            "Hangfire": "Information"
        }
    },

    "AllowedHosts": "*",

    "postgresqlconnection": {
        "connectionString": "Server=**.**.***.***;Port=5432;Database=Min;User Id=postgres;Password=min***;" //server
        //"connectionString": "Host=localhost;Port=5432;Database=Min;User Id=postgres;Password=*****;" // local
    },

    "mongoconnection": {
        "connectionString": "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false",
        "database": "backlog",
        "collection": "rawData",
        "collectionpMedian": "resultPmedian",
        "collectionClustering": "resultClustering"
    },

    "urlSettings": {
        "staticPageUrl": "http://**.**.***.***",
        "backendUrl": "http://**.**.***.***"
    },

    "variousSettings": {
        "defaultMessage": "A default message if nothing is found in the database."
    }
}

My startup.cs

services.AddHangfire(configuration => configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UsePostgreSqlStorage(Configuration.GetConnectionString("HangfireConnection")));

My DataContext.cs

private readonly IConfiguration Configuration;

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

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    // connect to postgress database
    var connectionString = Configuration["postgresqlconnection:connectionString"];

    options.UseNpgsql(connectionString);
}

The error

root@ubuntu-4gb:/# /usr/bin/dotnet /var/www/MinAPI/MinWebApi.dll
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
   at Hangfire.PostgreSql.PostgreSqlStorage..ctor(String connectionString, Action`1 connectionSetup, PostgreSqlStorageOptions options)
   at Hangfire.PostgreSql.PostgreSqlBootstrapperConfigurationExtensions.UsePostgreSqlStorage(IGlobalConfiguration configuration, String connectionString, Action`1 connectionSetup, PostgreSqlStorageOptions options)
   at Hangfire.PostgreSql.PostgreSqlBootstrapperConfigurationExtensions.UsePostgreSqlStorage(IGlobalConfiguration configuration, String connectionString)
   at WebApi.Startup.<ConfigureServices>b__4_2(IGlobalConfiguration configuration) in D:\C Sharp\Startup.cs:line 46
   at Hangfire.HangfireServiceCollectionExtensions.<>c__DisplayClass0_0.<AddHangfire>b__0(IServiceProvider provider, IGlobalConfiguration config)
   at Hangfire.HangfireServiceCollectionExtensions.<>c__DisplayClass1_0.<AddHangfire>b__14(IServiceProvider serviceProvider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at Hangfire.HangfireServiceCollectionExtensions.ThrowIfNotConfigured(IServiceProvider serviceProvider)
   at Hangfire.HangfireServiceCollectionExtensions.CreateBackgroundJobServerHostedService(IServiceProvider provider, JobStorage storage, IEnumerable`1 additionalProcesses, BackgroundJobServerOptions options)
   at Hangfire.HangfireServiceCollectionExtensions.<>c__DisplayClass9_0.<AddHangfireServerInner>b__0(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitNoCache(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at WebApi.Program.Main(String[] args) in D:\C Sharp\Program.cs:line 12

I have tried to hardcode the string inside the functions but the same error happens, tried to

英文:

I have upgraded my API to be working with .NET 7 and Ubuntu 23.04, everything went fine, the API and database are connected on my local machine and I can send request, but when I publish and deploy the app to my server, it seems that it doesn't read the connectionString in appsetting.json .

Here is my appsettings.json

{
    &quot;AppSettings&quot;: {
        &quot;Secret&quot;: &quot;*************&quot;,
        &quot;EmailFrom&quot;: &quot;********&quot;,
        &quot;SmtpHost&quot;: &quot;v******&quot;,
        &quot;SmtpPort&quot;: 587,
        &quot;SmtpUser&quot;: &quot;a*****&quot;,
        &quot;SmtpPass&quot;: &quot;HJu******&quot;
    },

  &quot;ConnectionStrings&quot;: {
    &quot;WebApiDatabase&quot;: &quot;Data Source=WebApiDatabase.db&quot;,
    &quot;HangfireConnection&quot;: &quot;Server=**.**.***.***;Port=5432;Database=Min;User Id=postgres;Password=min***;&quot; //server
    //&quot;HangfireConnection&quot;: &quot;Host=localhost;Port=5432;Database=Min;User Id=postgres;Password=*****;&quot; // local
  },

    &quot;Logging&quot;: {
      &quot;LogLevel&quot;: {
        &quot;Default&quot;: &quot;Information&quot;,
        &quot;Microsoft&quot;: &quot;Warning&quot;,
        &quot;Microsoft.Hosting.Lifetime&quot;: &quot;Information&quot;,
        &quot;Hangfire&quot;: &quot;Information&quot;
      } 
    },

    &quot;AllowedHosts&quot;: &quot;*&quot;,

  &quot;postgresqlconnection&quot;: {
    &quot;connectionString&quot;: &quot;Server=**.**.***.***;Port=5432;Database=Min;User Id=postgres;Password=min***;&quot; //server
    //&quot;connectionString&quot;: &quot;Host=localhost;Port=5432;Database=Min;User Id=postgres;Password=*****;&quot; // local
  },

    &quot;mongoconnection&quot;: {
        &quot;connectionString&quot;: &quot;mongodb://localhost:27017/?readPreference=primary&amp;appname=MongoDB%20Compass%20Community&amp;ssl=false&quot;,
        &quot;database&quot;: &quot;backlog&quot;,
        &quot;collection&quot;: &quot;rawData&quot;,
        &quot;collectionpMedian&quot;: &quot;resultPmedian&quot;,
        &quot;collectionClustering&quot;: &quot;resultClustering&quot;
    },

    &quot;urlSettings&quot;: {
        &quot;staticPageUrl&quot;: &quot;http://**.**.***.***&quot;,
        &quot;backendUrl&quot;: &quot;http://**.**.***.***&quot;
    },

    &quot;variousSettings&quot;: {
        &quot;defaultMessage&quot;: &quot;A default message if nothing is found in the database.&quot;
    }
}

My startup.cs

services.AddHangfire(configuration =&gt; configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UsePostgreSqlStorage(Configuration.GetConnectionString(&quot;HangfireConnection&quot;)));

My DataContext.cs

private readonly IConfiguration Configuration;

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

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // connect to postgress database
            var connectionString = Configuration[&quot;postgresqlconnection:connectionString&quot;];

            options.UseNpgsql(connectionString);
        }

The error

root@ubuntu-4gb:/# /usr/bin/dotnet /var/www/MinAPI/MinWebApi.dll
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter &#39;connectionString&#39;)
   at Hangfire.PostgreSql.PostgreSqlStorage..ctor(String connectionString, Action`1 connectionSetup, PostgreSqlStorageOptions options)
   at Hangfire.PostgreSql.PostgreSqlBootstrapperConfigurationExtensions.UsePostgreSqlStorage(IGlobalConfiguration configuration, String connectionString, Action`1 connectionSetup, PostgreSqlStorageOptions options)
   at Hangfire.PostgreSql.PostgreSqlBootstrapperConfigurationExtensions.UsePostgreSqlStorage(IGlobalConfiguration configuration, String connectionString)
   at WebApi.Startup.&lt;ConfigureServices&gt;b__4_2(IGlobalConfiguration configuration) in D:\C Sharp\Startup.cs:line 46
   at Hangfire.HangfireServiceCollectionExtensions.&lt;&gt;c__DisplayClass0_0.&lt;AddHangfire&gt;b__0(IServiceProvider provider, IGlobalConfiguration config)
   at Hangfire.HangfireServiceCollectionExtensions.&lt;&gt;c__DisplayClass1_0.&lt;AddHangfire&gt;b__14(IServiceProvider serviceProvider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at Hangfire.HangfireServiceCollectionExtensions.ThrowIfNotConfigured(IServiceProvider serviceProvider)
   at Hangfire.HangfireServiceCollectionExtensions.CreateBackgroundJobServerHostedService(IServiceProvider provider, JobStorage storage, IEnumerable`1 additionalProcesses, BackgroundJobServerOptions options)
   at Hangfire.HangfireServiceCollectionExtensions.&lt;&gt;c__DisplayClass9_0.&lt;AddHangfireServerInner&gt;b__0(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitNoCache(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.&lt;&gt;c__DisplayClass2_0.&lt;RealizeService&gt;b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at WebApi.Program.Main(String[] args) in D:\C Sharp\Program.cs:line 12

I have tried to hardcode the string inside the functions but the same error happens, tried to change variable name the same, tried to update the appsettings.Development.json to be the same as appsetting.json, it worked but when I restart the app service the error appears again.

Please guide me.

答案1

得分: 1

请验证您的Appsettings文件是否实际上已经发布?
另外,只有在IDE(如Visual Studio等)本地运行时才会读取Appsettings.Development.Json。否则,它将尝试读取Appsettings.Json或Appsettings.Production.Json。

英文:

Can you please verify that your Appsettings file is actually being published?
Also Appsettings.Development.Json is only read when running locally in an IDE(Visual Studios, ETC). Otherwise it will try and read Appsettings.Json or Appsettings.Production.Json

答案2

得分: 0

错误每次我在服务器上更新API时都会出现,但我发现只要编辑服务器上的appsettings.json,问题就会解决,但只有在那个时候才有效,而且我每次都需要这样做,不过可以忽略,因为API运行得非常正常。

英文:

The error kept appearing every time I update the API on the server, however I found that editing the appsettings.json within the server solves the problem for that time only, and I need to do that every time, however, It can be ignored as the API works perfeclty fine.

huangapple
  • 本文由 发表于 2023年6月14日 23:36:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定