How To Access Azure Function App ConnectionString

2019-04-30 02:06发布

问题:

My Azure Function App has a ConnectionString defined. I want to retrieve it from a C# function written in dotnet standard 2.0. I have tried adding System.Configuration.ConfigurationManager to the project.json and using

var str = ConfigurationManager.ConnectionStrings["my string"].ConnectionString;

but I get the error

run.csx(24,15): error CS0103: The name 'ConfigurationManager' does not exist in the current context

How do I access the connection string?

回答1:

ConfigurationManager is not available in Azure Functions v2 .NET Standard projects. Azure FUnction v2 now uses ASPNET Core Configuration.

You can follow these instructions.

  1. Add the 3rd parameter in your run method.

    public static async Task<HttpResponseMessage> Run(InputMessage req, TraceWriter log, ExecutionContext context)
    
  2. In the run method, add the following code.

    var config = new ConfigurationBuilder()
        .SetBasePath(context.FunctionAppDirectory)
        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables()
        .Build();
    
  3. Then you can use this variable to access app settings.

You can see this blog for instructions on how to use AppSettings and ConnectionStrings in v2.



回答2:

run.csx(24,15): error CS0103: The name 'ConfigurationManager' does not exist in the current context

According to mentioned expception. It seems that you need to add reference System.Configuration in the dotnet standard 2.0 class library. I test it locally it works correctly on my side.

public class TestGetConnectionString
{

    public string ConnectionString;

    public TestGetConnectionString()
    { 

        var str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        ConnectionString = str;
    }


}

Update:

In your case you also could add the connection string in the Azure function appsetting. Details you could refer to the screenshot. And we could access it easily by the following code.

 var connectionstring = Environment.GetEnvironmentVariable("ConnectionString");

Test it on the azure portal.