EF Core 2.0 connection string in Azure Functions .NET Core

耗尽温柔 提交于 2019-11-28 00:17:44

问题


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



来源:https://stackoverflow.com/questions/47806064/ef-core-2-0-connection-string-in-azure-functions-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!