Events
Take the Microsoft Learn Challenge
Nov 19, 11 PM - Jan 10, 11 PM
Ignite Edition - Build skills in Microsoft Azure and earn a digital badge by January 10!
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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:
ASP.NET Core apps that connect to Azure services generally depend on the following Azure SDK client libraries:
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.
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 the Microsoft.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.
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 the Microsoft.Extensions.Azure
library to set a shared DefaultAzureCredential
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 which DefaultAzureCredential
scans for credentials, see DefaultAzureCredential overview. Using a shared DefaultAzureCredential
instance ensures the underlying token cache is used, which improves application resilience and performance due to fewer requests for a new token.
Azure SDK service clients support configurations to change their default behaviors. There are two ways to configure service clients:
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.
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:
KeyVault
, ServiceBus
, and Storage
, are arbitrary names used to reference the config sections from your code. You will pass these names to AddClient
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.KeyVault:VaultUri
, ServiceBus:Namespace
, and Storage:ServiceUri
key values map to the arguments of the SecretClient(Uri, TokenCredential, SecretClientOptions), ServiceBusClient(String), and BlobServiceClient(Uri, TokenCredential, BlobClientOptions) constructor overloads, respectively. The TokenCredential
variants of the constructors are used because a default TokenCredential
is set via the UseCredential(TokenCredential) method call.Update the the Program.cs
file to retrieve the JSON file configurations using IConfiguration
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"]);
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 the ConfigureDefaults
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"));
});
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"
}
}
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Take the Microsoft Learn Challenge
Nov 19, 11 PM - Jan 10, 11 PM
Ignite Edition - Build skills in Microsoft Azure and earn a digital badge by January 10!
Register nowTraining
Module
Capture Web Application Logs with App Service Diagnostics Logging - Training
Learn about how to capture trace output from your Azure web apps. View a live log stream and download logs files for offline analysis.
Certification
Microsoft Certified: Azure Developer Associate - Certifications
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.