简体   繁体   中英

ASP.NET Core on Azure App Service not reading Connection string from Application settings

How to force App Service to read connection string from settings, and not from the appsettings.json file?

We've tried Settings/Application Settings/Connection Strings and Settings/Configuration (preview)/Connection strings, but it keeps reading from uploaded appsettings.json.

We've using Azure DevOps and tried Web One Click Publish. Probably it would with work with manual publish and connection string replacement directly from publish settings (in VS).

We used this approach for other (non-asp.net core) WebSites, and it works as it should.

I've checked tutorials for Asp.Net Core and Azure Hosting, and I believe I did everything right?

Where do I even start to debug this thing?

EntityFramework is in a separate project, we're using dependency injection with a custom constructor for the connection string, and it works just fine if I setup appsettings.json file manually, but I have to deploy it on multiple servers, and it would not make much sense to this stuff from code or manually each time. And I wouldn't like to exclude auto deployment of appsettings.json, I just want to transform it on the server.

ConfigureServices

IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "xxx"
  },
...

Perhaps I'm reading appsetting.json wrong, and Azure cannot inject new connection string properly?

Based on the discussion in the comments, the solution was to use the IConfiguration object provided via the Startup class constructor (this only works in Core 2.x+).

So for example:

private readonly IConfiguration _config;

public Startup(IConfiguration config)
{
    _config = config;
}

You can then use _config to access settings within Startup .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM