In this Azure SDK for .NET, we will show you how to connect to Azure from a .NET application.
The Azure REST API platform allows us to connect to Azure using multiple clients, which include:
- API Clients (Postman, etc)
- PowerShell (Az module)
- Azure CLI
- .NET application (Using Azure SDK for .NET)
The Azure SDK for .NET can create and manage any aspect of Azure from within a .NET application, such as C#, ASP, Blazor, and more.
In this post, we will create a C# application that connects to Azure by utilizing the Microsoft Azure Resources management core library and creating an ArmClient class that handles the authentication layer to Azure.
Prerequisites
- Before continuing, you must create an Azure Service Principal with permission from the owner or contributor.
- Create environment variables for the following variables that belong to the Service Principal
AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
If you are using PowerShell, you can create them using the following commands (variables are only valid for the duration of the session and are not permanent)
$env:AZURE_TENANT_ID ="value"
$env:AZURE_CLIENT_ID ="value"
$env:AZURE_CLIENT_SECRET ="value"
Connect to Azure
To connect to Azure using the SDK, create a C# application and install the following library.
dotnet add package Azure.ResourceManager
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Azure
Add the following code to your Program.cs
. The program will print the default Azure subscription to the screen.
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.ResourceManager.Storage.Models;
using Azure.ResourceManager.Resources;
using Azure.Core;
using Azure.ResourceManager;
// Create an instance of the ArmClient using the DefaultAzureCredential.
// The DefaultAzureCredential will use the available authentication methods
// to authenticate the client, such as environment variables, managed identity,
// or interactive login.
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
var subdetails = armClient.GetDefaultSubscription();
Console.WriteLine ($"The default Azure subscription is {subdetails.Id}");
Save the file and run the application using dotnet run
Related Articles
- Authenticate to Azure Using Azure SDK for .NET and Armclient
- Check Which .NET Core SDK Version is Installed
- How To Install .NET Core 2.0 SDK On Windows Server Core 2016 1709
- DevOps – Run .NET Core 3.0 Applications with Visual Studio 2019
- Disable Azure AD Security Defaults With PowerShell