Uwaga
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
This quickstart shows you how to centralize and manage your Azure Functions application settings outside of your code using Azure App Configuration. With the .NET configuration provider integration, you can add App Configuration as an extra configuration source with just a few simple code changes.
Prerequisites
- An Azure account with an active subscription. Create one for free.
- An App Configuration store. Create a store.
- Visual Studio with the Azure development workload.
- Azure Functions tools.
Add a key-value
Add the following key-value to the App Configuration store and leave Label and Content Type with their default values. For more information about how to add key-values to a store using the Azure portal or the CLI, go to Create a key-value.
Key | Value |
---|---|
TestApp:Settings:Message | Data from Azure App Configuration |
Utwórz aplikację funkcjonalną
Utwórz aplikację usługi Azure Functions przy użyciu programu Visual Studio, wybierając szablon usługi Azure Functions (C#). Ten szablon przeprowadzi Cię przez proces konfigurowania podstawowych ustawień projektu. Aby uzyskać szczegółowe instrukcje, zobacz Tworzenie usługi Azure Functions przy użyciu programu Visual Studio.
Użyj poniższej tabeli jako odwołania do kluczowych parametrów podczas tworzenia aplikacji funkcji.
Setting | Value |
---|---|
Functions worker | .NET 8.0 Isolated |
Funkcja | Wyzwalacz HTTP |
Poziom autoryzacji | Anonim |
Note
Usługa Azure App Configuration może być używana z usługą Azure Functions w modelu izolowanego procesu roboczego lub w modelu procesu. This quickstart uses the isolated worker model as an example. Kompletne przykłady kodu dla obu modeli można znaleźć w repozytorium GitHub usługi Azure App Configuration.
Connect to an App Configuration store
You can connect to your App Configuration store using Microsoft Entra ID (recommended), or a connection string.
Right-click your project, and select Manage NuGet Packages. Na karcie Przeglądaj wyszukaj i dodaj do projektu najnowszą stabilną wersję następujących pakietów NuGet.
- Microsoft.Azure.AppConfiguration.Functions.Worker
- Azure.Identity
Otwórz Program.cs i zaktualizuj kod w następujący sposób. You add Azure App Configuration as an additional configuration source by calling the
AddAzureAppConfiguration
method.Aby się uwierzytelnić w sklepie App Configuration, używasz
DefaultAzureCredential
. Postępuj zgodnie z instrukcjami, aby przypisać swoje poświadczenie do roli Czytelnika danych konfiguracji aplikacji. Be sure to allow sufficient time for the permission to propagate before running your application.using Azure.Identity; using Microsoft.Azure.Functions.Worker.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; var builder = FunctionsApplication.CreateBuilder(args); // Connect to Azure App Configuration builder.Configuration.AddAzureAppConfiguration(options => { Uri endpoint = new(Environment.GetEnvironmentVariable("AZURE_APPCONFIG_ENDPOINT") ?? throw new InvalidOperationException("The environment variable 'AZURE_APPCONFIG_ENDPOINT' is not set or is empty.")); options.Connect(endpoint, new DefaultAzureCredential()) // Load all keys that start with `TestApp:` and have no label .Select("TestApp:*"); });
Otwórz Function1.cs i dodaj następującą przestrzeń nazw.
using Microsoft.Extensions.Configuration;
Update the constructor to obtain an instance of
IConfiguration
through dependency injection.private readonly IConfiguration _configuration; private readonly ILogger<Function1> _logger; public Function1(IConfiguration configuration, ILogger<Function1> logger) { _configuration = configuration; _logger = logger; }
Update the
Run
method to read values from the configuration.[Function("Function1")] public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req) { _logger.LogInformation("C# HTTP trigger function processed a request."); // Read configuration data string key = "TestApp:Settings:Message"; string? message = _configuration[key]; return new OkObjectResult(message ?? $"Please create a key-value with the key '{key}' in Azure App Configuration."); }
Test the function locally
Ustaw zmienną środowiskową .
Ustaw zmienną środowiskową o nazwie AZURE_APPCONFIG_ENDPOINT na punkt końcowy Twojego sklepu App Configuration, który znajdziesz w sekcji Przegląd w portalu Azure.
If you use the Windows command prompt, run the following command and restart the command prompt to allow the change to take effect:
setx AZURE_APPCONFIG_ENDPOINT "<endpoint-of-your-app-configuration-store>"
Jeśli używasz programu PowerShell, uruchom następujące polecenie:
$Env:AZURE_APPCONFIG_ENDPOINT = "<endpoint-of-your-app-configuration-store>"
If you use macOS or Linux, run the following command:
export AZURE_APPCONFIG_ENDPOINT='<endpoint-of-your-app-configuration-store>'
Press F5 to test your function. If prompted, accept the request from Visual Studio to download and install Azure Functions Core (CLI) tools. You might also need to enable a firewall exception so that the tools can handle HTTP requests.
Copy the URL of your function from the Azure Functions runtime output.
Paste the URL for the HTTP request into your browser's address bar. The following image shows the response in the browser to the local GET request returned by the function.
Manage trigger parameters with App Configuration references
Azure Functions triggers define how a function is invoked. Trigger attributes, such as queue names or database names, are loaded at host startup time and can't directly retrieve values from Azure App Configuration. To manage these parameters, you can use the App Configuration reference feature available for Azure Functions and App Service.
The App Configuration reference feature allows you to reference key-values stored in Azure App Configuration directly from your application settings. Azure Functions resolves these references at startup, enabling you to manage trigger parameters centrally and securely.
For example, consider a queue-triggered Function app. Instead of specifying the queue name directly in the trigger attribute, you can reference a key-value stored in Azure App Configuration.
In your Azure App Configuration store, add a key-value for your queue name:
Key Value TestApp:Storage:QueueName <The queue name in your storage account> In your Function app, select Settings ->Environment variables ->App settings in the Azure portal, and create an application setting that references the App Configuration key:
Nazwa Value MyQueueName @Microsoft.AppConfiguration(Endpoint=<your-store-endpoint>; Key=TestApp:Storage:QueueName)
Tip
If you have multiple key-values in Azure App Configuration, you can export them in batch as App Configuration references to Azure Functions using the Azure portal or CLI.
Enable the managed identity for your Azure Functions app and assign it the App Configuration Data Reader role for your App Configuration store. For detailed instructions on setting up App Configuration references, see Use App Configuration references in App Service and Azure Functions.
Update your queue-triggered function to use the application setting:
[Function("QueueTriggeredFunction")] public void Run([QueueTrigger(queueName: "%MyQueueName%")] QueueMessage message) { _logger.LogInformation($"C# Queue trigger function processed: {message.MessageText}"); }
At runtime, Azure Functions resolves the
%MyQueueName%
placeholder to the value stored in Azure App Configuration, allowing you to manage trigger parameters centrally without hardcoding them into your function code.
Clean up resources
If you don't want to continue using the resources created in this article, delete the resource group you created here to avoid charges.
Important
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Ensure that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.
- Sign in to the Azure portal, and select Resource groups.
- In the Filter by name box, enter the name of your resource group.
- In the result list, select the resource group name to see an overview.
- Select Delete resource group.
- You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select Delete.
After a few moments, the resource group and all its resources are deleted.
Next steps
In this quickstart, you integrated Azure App Configuration with an Azure Functions app. To learn how to enable your Function app to dynamically refresh configuration settings, continue to the next tutorial.
Aby dowiedzieć się, jak używać flag funkcji z usługi Azure App Configuration w aplikacji usługi Azure Functions, przejdź do następującego samouczka.
Aby dowiedzieć się, jak używać tożsamości zarządzanej platformy Azure w celu usprawnienia dostępu do usługi App Configuration, przejdź do następującego samouczka.