Use the Azure SDK for .NET in ASP.NET Core apps
The Azure SDK for .NET enables ASP.NET Core apps to integrate with many different Azure services. In this article, you'll learn best practices and the steps to adopt the Azure SDK for .NET in your ASP.NET Core apps. You'll learn how to:
- Register services for dependency injection.
- Authenticate to Azure without using passwords or secrets.
- Implement centralized, standardized configuration.
- Configure common web app concerns such as logging and retries.
Explore common Azure SDK client libraries
ASP.NET Core apps that connect to Azure services generally depend on the following Azure SDK client libraries:
- Microsoft.Extensions.Azure provides helper methods to register clients with the dependency injection service collection and handles various concerns for you, such as setting up logging, handling DI service lifetimes, and authentication credential management.
- Azure.Identity enables Microsoft Entra ID authentication support across the Azure SDK. It provides a set of TokenCredential implementations to construct Azure SDK clients that support Microsoft Entra authentication.
Azure.<service-namespace>
libraries, such as Azure.Storage.Blobs and Azure.Messaging.ServiceBus, provide service clients and other types to help you connect to and consume specific Azure services. For a complete inventory of these libraries, see Libraries using Azure.Core.
In the sections ahead, you'll explore how to implement an ASP.NET Core application that uses these libraries.
Register Azure SDK clients with the DI service collection
The Azure SDK for .NET client libraries provide service clients to connect your app to Azure services such as Azure Blob Storage and Azure Key Vault. Register these services with the dependency container in the Program.cs
file of your app to make them available via dependency injection.
Complete the following steps to register the services you need:
Add the Microsoft.Extensions.Azure package:
dotnet add package Microsoft.Extensions.Azure
Add the relevant
Azure.*
service client packages:dotnet add package Azure.Security.KeyVault.Secrets dotnet add package Azure.Storage.Blobs dotnet add package Azure.Messaging.ServiceBus
In the
Program.cs
file of your app, invoke the AddAzureClients extension method from theMicrosoft.Extensions.Azure
library to register a client to communicate with each Azure service. Some client libraries provide additional subclients for specific subgroups of Azure service functionality. You can register such subclients for dependency injection via the AddClient extension method.builder.Services.AddAzureClients(clientBuilder => { // Register a client for each Azure service using inline configuration clientBuilder.AddSecretClient(new Uri("<key_vault_url>")); clientBuilder.AddBlobServiceClient(new Uri("<storage_url>")); clientBuilder.AddServiceBusClientWithNamespace( "<your_namespace>.servicebus.windows.net"); // Register a subclient for each Azure Service Bus Queue var queueNames = new string[] { "queue1", "queue2" }; foreach (string queue in queueNames) { clientBuilder.AddClient<ServiceBusSender, ServiceBusClientOptions>( (_, _, provider) => provider.GetService<ServiceBusClient>() .CreateSender(queue)).WithName(queue); } // Register a shared credential for Microsoft Entra ID authentication clientBuilder.UseCredential(new DefaultAzureCredential()); });
Inject the registered clients into your ASP.NET Core app components, services, or API endpoint:
app.MapGet("/reports", async ( BlobServiceClient blobServiceClient, IAzureClientFactory<ServiceBusSender> senderFactory) => { // Create the named client ServiceBusSender serviceBusSender = senderFactory.CreateClient("queue1"); await serviceBusSender.SendMessageAsync(new ServiceBusMessage("Hello world")); // Use the blob client BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("reports"); List<BlobItem> reports = new(); await foreach (BlobItem blobItem in containerClient.GetBlobsAsync()) { reports.Add(blobItem); } return reports; }) .WithName("GetReports");
For more information, see Dependency injection with the Azure SDK for .NET.
Authenticate using Microsoft Entra ID
Token-based authentication with Microsoft Entra ID is the recommended approach to authenticate requests to Azure services. To authorize those requests, Azure role-based access control (RBAC) manages access to Azure resources based on a user's Microsoft Entra identity and assigned roles.
Use the Azure Identity library for the aforementioned token-based authentication support. The library provides classes such as DefaultAzureCredential
to simplify configuring secure connections. DefaultAzureCredential
supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code. Visit the Authentication section of the Azure SDK for .NET docs for more details on these topics.
Note
Many Azure services also allow you to authorize requests using keys. However, this approach should be used with caution. Developers must be diligent to never expose the access key in an unsecure location. Anyone who has the access key can authorize requests against the associated Azure resource.
Add the Azure.Identity package:
dotnet add package Azure.Identity
In the
Program.cs
file of your app, invoke the UseCredential extension method from theMicrosoft.Extensions.Azure
library to set a sharedDefaultAzureCredential
instance for all registered Azure service clients:builder.Services.AddAzureClients(clientBuilder => { // Register a client for each Azure service using inline configuration clientBuilder.AddSecretClient(new Uri("<key_vault_url>")); clientBuilder.AddBlobServiceClient(new Uri("<storage_url>")); clientBuilder.AddServiceBusClientWithNamespace( "<your_namespace>.servicebus.windows.net"); // Register a subclient for each Azure Service Bus Queue var queueNames = new string[] { "queue1", "queue2" }; foreach (string queue in queueNames) { clientBuilder.AddClient<ServiceBusSender, ServiceBusClientOptions>( (_, _, provider) => provider.GetService<ServiceBusClient>() .CreateSender(queue)).WithName(queue); } // Register a shared credential for Microsoft Entra ID authentication clientBuilder.UseCredential(new DefaultAzureCredential()); });
DefaultAzureCredential
discovers available credentials in the current environment and uses them to authenticate to Azure services. For the order and locations in whichDefaultAzureCredential
scans for credentials, see DefaultAzureCredential overview. Using a sharedDefaultAzureCredential
instance ensures the underlying token cache is used, which improves application resilience and performance due to fewer requests for a new token.
Apply configurations
Azure SDK service clients support configurations to change their default behaviors. There are two ways to configure service clients:
- JSON configuration files are generally the recommended approach because they simplify managing differences in app deployments between environments.
- Inline code configurations can be applied when you register the service client. For example, in the Register clients and subclients section, you explicitly passed the URI variables to the client constructors.
IConfiguration
precedence rules are respected by the Microsoft.Extensions.Azure
extension methods, which are detailed in the Configuration Providers documentation.
Complete the steps in the following sections to update your app to use JSON file configuration for the appropriate environments. Use the appsettings.Development.json
file for development settings and the appsettings.Production.json
file for production environment settings. You can add configuration settings whose names are public properties on the ClientOptions class to the JSON file.
Configure registered services
Update the
appsettings.<environment>.json
file in your app with the highlighted service configurations:{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Azure.Messaging.ServiceBus": "Debug" } }, "AzureDefaults": { "Diagnostics": { "IsTelemetryDisabled": false, "IsLoggingContentEnabled": true }, "Retry": { "MaxRetries": 3, "Mode": "Exponential" } }, "KeyVault": { "VaultUri": "https://<your-key-vault-name>.vault.azure.net" }, "ServiceBus": { "Namespace": "<your_service-bus_namespace>.servicebus.windows.net" }, "Storage": { "ServiceUri": "https://<your-storage-account-name>.storage.windows.net" } }
In the preceding JSON sample:
- The top-level key names,
KeyVault
,ServiceBus
, andStorage
, are arbitrary names used to reference the config sections from your code. You will pass these names toAddClient
extension methods to configure a given client. All other key names map to specific client options, and JSON serialization is performed in a case-insensitive manner. - The
KeyVault:VaultUri
,ServiceBus:Namespace
, andStorage:ServiceUri
key values map to the arguments of the SecretClient(Uri, TokenCredential, SecretClientOptions), ServiceBusClient(String), and BlobServiceClient(Uri, TokenCredential, BlobClientOptions) constructor overloads, respectively. TheTokenCredential
variants of the constructors are used because a defaultTokenCredential
is set via the UseCredential(TokenCredential) method call.
- The top-level key names,
Update the the
Program.cs
file to retrieve the JSON file configurations usingIConfiguration
and pass them into your service registrations:builder.Services.AddAzureClients(clientBuilder => { // Register clients using a config file section clientBuilder.AddSecretClient( builder.Configuration.GetSection("KeyVault")); clientBuilder.AddBlobServiceClient( builder.Configuration.GetSection("Storage")); // Register clients using a specific config key-value pair clientBuilder.AddServiceBusClientWithNamespace( builder.Configuration["ServiceBus:Namespace"]);
Configure Azure defaults and retries
You may want to change default Azure client configurations globally or for a specific service client. For example, you may want different retry settings or to use a different service API version. You can set the retry settings globally or on a per-service basis.
Update your configuration file to set default Azure settings, such as a new default retry policy that all registered Azure clients will use:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Azure.Messaging.ServiceBus": "Debug" } }, "AzureDefaults": { "Diagnostics": { "IsTelemetryDisabled": false, "IsLoggingContentEnabled": true }, "Retry": { "MaxRetries": 3, "Mode": "Exponential" } }, "KeyVault": { "VaultUri": "https://<your-key-vault-name>.vault.azure.net" }, "ServiceBus": { "Namespace": "<your_service-bus_namespace>.servicebus.windows.net" }, "Storage": { "ServiceUri": "https://<your-storage-account-name>.storage.windows.net" } }
In the
Program.cs
file, call theConfigureDefaults
extension method to retrieve the default settings and apply them to your service clients:builder.Services.AddAzureClients(clientBuilder => { // Register clients using a config file section clientBuilder.AddSecretClient( builder.Configuration.GetSection("KeyVault")); clientBuilder.AddBlobServiceClient( builder.Configuration.GetSection("Storage")); // Register clients using a specific config key-value pair clientBuilder.AddServiceBusClientWithNamespace( builder.Configuration["ServiceBus:Namespace"]); // Register a subclient for each Azure Service Bus Queue string[] queueNames = [ "queue1", "queue2" ]; foreach (string queue in queueNames) { clientBuilder.AddClient<ServiceBusSender, ServiceBusClientOptions>( (_, _, provider) => provider.GetService<ServiceBusClient>() .CreateSender(queue)).WithName(queue); } clientBuilder.UseCredential(new DefaultAzureCredential()); // Set up any default settings clientBuilder.ConfigureDefaults( builder.Configuration.GetSection("AzureDefaults")); });
Configure logging
The Azure SDK for .NET client libraries can log client library operations to monitor requests and responses to Azure services. Client libraries can also log a variety of other events, including retries, token retrieval, and service-specific events from various clients. When you register an Azure SDK client using the AddAzureClients extension method, the AzureEventSourceLogForwarder is registered with the dependency injection container. The AzureEventSourceLogForwarder
forwards log messages from Azure SDK event sources to ILoggerFactory to enables you to use the standard ASP.NET Core logging configuration for logging.
The following table depicts how the Azure SDK for .NET EventLevel
maps to the ASP.NET Core LogLevel
. For more information on these topics and other scenarios, see Logging with the Azure SDK for .NET and Dependency injection with the Azure SDK for .NET.
Azure SDK EventLevel |
ASP.NET Core LogLevel |
---|---|
Critical |
Critical |
Error |
Error |
Informational |
Information |
Warning |
Warning |
Verbose |
Debug |
LogAlways |
Information |
You can change default log levels and other settings using the same JSON configurations outlined in the configure authentication section. For example, toggle the ServiceBusClient
log level to Debug
by setting the Logging:LogLevel:Azure.Messaging.ServiceBus
key as follows:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Azure.Messaging.ServiceBus": "Debug"
}
},
"AzureDefaults": {
"Diagnostics": {
"IsTelemetryDisabled": false,
"IsLoggingContentEnabled": true
},
"Retry": {
"MaxRetries": 3,
"Mode": "Exponential"
}
},
"KeyVault": {
"VaultUri": "https://<your-key-vault-name>.vault.azure.net"
},
"ServiceBus": {
"Namespace": "<your_service-bus_namespace>.servicebus.windows.net"
},
"Storage": {
"ServiceUri": "https://<your-storage-account-name>.storage.windows.net"
}
}