Accessing Application Settings and connection strings in the Azure Function code

Perform the following steps:

  1. Create a configuration items with the MyAppSetting key and a ConnectionStrings with the sqldb_connection key in the local.settings.json file. local.settings.json should look something like the following screenshot:

  1. Replace the existing code with the following code. We have added a few lines that read the configuration values and the connection strings:
public class HttpTriggerCSharpFromVS
{
[FunctionName("HttpTriggerCSharpFromVS")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req,ILogger logger)
{
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", true)
.Build();
var ValueFromGetConnectionStringOrSetting = configuration.GetConnectionStringOrSetting("MyAppSetting");
logger.LogInformation("GetConnectionStringOrSetting" + ValueFromGetConnectionStringOrSetting);
var ValueFromConfigurationIndex= configuration["MyAppSetting"];
logger.LogInformation("ValueFromConfigurationIndex" + ValueFromConfigurationIndex);
var ValueFromConnectionString = configuration.GetConnectionStringOrSetting("ConnectionStrings:sqldb_connection");
logger.LogInformation("ConnectionStrings:sqldb_connection" + ValueFromConnectionString);
string name = req.Query["name"];
return name != null ? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
  1. Publish the project to Azure by right-clicking on the project and then clicking on Publish in the menu.
  2. Add the configuration key and the connection string in the Application Settings blade:

  1. Run the function by clicking on the Run button, which logs the output in the Output window: