API in . NET Core - api does not find connection string from appsettings.json

Asked

Viewed 40 times

0

I did all the development on a windows machine but after almost a week I was able to deploy on a Ubuntu 18.04 machine and set the settings to access via https.

But now I came across the following error when I need to connect to the bank.

Argumentnullexception: Value cannot be null. (Parameter 'connectionString')

Before the server and ssl related changes the connection string was coming with the value but now it comes null

My Program.Cs

public class Program ( a parte com mais mudanças para o deploy)
{
    public static void Main(string[] args)
    {
       var host = new WebHostBuilder()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseUrls("https://*:5001;http://*:5000", "http://*:80")
        .UseKestrel(options =>
              {
                  options.ListenAnyIP(443, listenOptions =>
                  {
                      listenOptions.UseHttps("chave.pfx", "senha");
                  });
              })
        .UseStartup<Startup>()
        .Build();

        host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
     Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

In appsettings.json I create the string

     {
      "DbContextSettings": {
        "ConnectionString": "Host=host;Port=port;Pooling=true;Database=Banco;User Id=postgres;Password=******;"
      },
    }

In Startup.Cs I try to retrieve the string but here it is not getting the connection there from appsettings

   public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }    
    public void ConfigureServices(IServiceCollection services)
      {
         ...
         var connectionString = Configuration["DbContextSettings:ConnectionString"];
         services.AddDbContext<APIMeuContexto>(opts => opts.UseNpgsql(connectionString));
         ...
       }

I’d like to understand why appsettings is no longer being seen by the startup (since before the deployment api worked) and how to fix it. I imagine now he might be looking for appsettings.json somewhere else. But I don’t know how to figure that out.

  • The question was marked as duplicate but I didn’t understand the relationship between the two questions. The other question didn’t help me at all. What happens here is that my Startup does not find connectionstring in appsettings.json and the name is right, so my Startup.Cs is not seeing appsetting.json. As I said, before the settings made for the deploy was working.

  • 1

    I honestly didn’t understand the reason either... But your problem is that the appsettings file is not in the application directory. To confirm this (and usually is desirable) change the line of the AddJsonFile for .AddJsonFile("appsettings.json"). This way it will be mandatory to have an appsettings.js configuration file. There are some alternatives, but that would be the easiest way to confirm and then correct.

  • @tvdias But then, I’m using it anyway . Addjsonfile("appsettings.json") There at Startup. I have to put the whole way?

  • No, the problem is that the file should not be present and the application does not return error on account of the optional: true.

  • Remove the optional: true would be the 1st step to ensure that there is always the configuration file.

  • @tvdias I just discovered the problem. I had created a constructor that received IHostingEnvironment env without realizing that I already had what I received IConfiguration configuration And that’s where I was putting it and it didn’t read the command to add json. I tried to put in what I already had but ended up having another error.At the end I did another search and found the option to put in Program.Cs

  • 1

    I just wanted to understand why my signals are ignored. The question has nothing to do with the question posed as a reason for closing. And I still won a vote against. I just want someone to send me a really equal question. Or point out the real problem of my question.

  • I’m glad it worked out. These settings vary according to the framework version and, if I’m not mistaken, have versions that do not even need to specify the configuration file (using Defaultwebhostbuilder). The startup class idem, there are some particularities depending on the version.

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.