EF Core 2.0 connection string in Azure Functions .

2019-01-25 20:49发布

问题:

I'm using EF core 2.0 in Azure Functions using .net core. I'm trying to read db ConnectionString from local.settings.json, which is defined:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  },
  "ConnectionStrings": {
    "MyDbConnStr": "Data Source=.;Initial Catalog=xxxxxxx"
  }
}

Environment.GetEnvironmentVariable() doesn't return any connection string info neither I can use ConfigurationManager.ConnectionStrings with .net core. How do I access the connection string from the code?

回答1:

You could use one of the helper classes in Microsoft.Azure.WebJobs.Host:

AmbientConnectionStringProvider.Instance.GetConnectionString("MyDbConnStr")

This class is delegating the work to internal class called ConfigurationUtility, which does something in line with

var configuration = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .AddJsonFile("appsettings.json", true)
    .Build();
var conn = configuration.GetConnectionString("MyDbConnStr");


回答2:

You can use Environment.GetEnvironmentVariable. The keys are "ConnectionStrings:YourKey"

Assuming your local.settings.json looks like the following:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  },
  "ConnectionStrings": {
    "sqldb_connection": "connection_string_here"
  }
}

Use Environment.GetEnvironmentVariable("ConnectionStrings:sqldb_connection", EnvironmentVariableTarget.Process); to get the value