A Blob Storage endpoint forms the base address for all objects within a storage account. When you create a storage account, you specify which type of endpoint you want to use. Blob Storage supports two types of endpoints:
- A standard endpoint includes the unique storage account name along with a fixed domain name. The format of a standard endpoint is
https://<storage-account>.blob.core.windows.net.
- An Azure DNS zone endpoint (preview) dynamically selects an Azure DNS zone and assigns it to the storage account when it's created. The format of an Azure DNS Zone endpoint is
https://<storage-account>.z[00-99].blob.storage.azure.net.
When your application creates a service client object that connects to Blob Storage data resources, you pass a URI referencing the endpoint to the service client constructor. You can construct the URI string manually, or you can query for the service endpoint at runtime using the Azure Storage management library.
Important
Ao fazer referência a um ponto de extremidade de serviço em um aplicativo cliente, é recomendável evitar depender de um endereço IP armazenado em cache. O endereço IP da conta de armazenamento está sujeito a alterações e confiar em um endereço IP armazenado em cache pode resultar em um comportamento inesperado.
CNAMEs that are associated with a storage account endpoint can change without notice. Your application shouldn't take a dependency on the number of of CNAME records or the sub-domains that are associated with those CNAME records.
Além disso, é recomendável que você honre o tempo de vida (TTL) do registro DNS e evite substituí-lo. Sobrepor o TTL DNS pode resultar em comportamento inesperado.
For more information, see CNAME records, subdomains and IP addresses.
The Azure Storage management library provides programmatic access to the Azure Storage resource provider. The resource provider is the Azure Storage implementation of the Azure Resource Manager. The management library enables developers to manage storage accounts and account configuration, as well as configure lifecycle management policies, object replication policies, and immutability policies.
In this article, you learn how to query a Blob Storage endpoint using the Azure Storage management library. Then you use that endpoint to create a BlobServiceClient object to connect with Blob Storage data resources.
Configure o seu projeto
Para trabalhar com os exemplos de código neste artigo, siga estas etapas para configurar seu projeto.
Instalar pacotes
Install packages to work with the libraries used in this example.
Instale os seguintes pacotes usando dotnet add package:
dotnet add package Azure.Identity
dotnet add package Azure.ResourceManager.Storage
dotnet add package Azure.Storage.Blobs
Abra o ficheiro pom.xml no seu editor de texto.
Adicione azure-sdk-bom para depender da versão mais recente da biblioteca. No trecho a seguir, substitua o espaço reservado {bom_version_to_target} pelo número da versão. Usar azure-sdk-bom evita que você precise especificar a versão de cada dependência individual. Para saber mais sobre o BOM, consulte o arquivo README do BOM do SDK do Azure.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-sdk-bom</artifactId>
<version>{bom_version_to_target}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Em seguida, adicione os seguintes elementos de dependência ao grupo de dependências. A dependência azure-identity é necessária para ligações sem palavra-passe aos serviços do Azure.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-storage-blob</artifactId>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
</dependency>
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager</artifactId>
<version>2.24.0</version>
</dependency>
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager-storage</artifactId>
<version>2.24.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-management</artifactId>
<version>1.10.2</version>
</dependency>
Instale os seguintes pacotes usando npm install:
npm install @azure/identity
npm install @azure/storage-blob
npm install @azure/arm-resources
npm install @azure/arm-storage
Instale os seguintes pacotes usando pip install:
pip install azure-identity
pip install azure-storage-blob
pip install azure-mgmt-resource
pip install azure-mgmt-storage
Configurar o código do aplicativo
Add the necessary using or import directives to the code. Note that the code examples may split out functionality between files, but in this section all directives are listed together.
Aditar as seguintes using diretivas:
using Azure.Core;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Storage;
Client library information:
-
Azure.Identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
-
Azure.ResourceManager.Storage: Supports management of Azure Storage resources, including resource groups and storage accounts.
-
Azure.Storage.Blobs: Contains the primary classes that you can use to work with Blob Storage data resources.
Aditar as seguintes import diretivas:
import com.azure.identity.*;
import com.azure.storage.blob.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.models.*;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;
Client library information:
Add the following require statements to load the modules:
const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");
const { ResourceManagementClient } = require("@azure/arm-resources");
const { StorageManagementClient } = require("@azure/arm-storage");
Client library information:
-
@azure/identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
-
@azure/storage-blob: Contains the primary classes that you can use to work with Blob Storage data resources.
-
@azure/arm-resources: Supports management of Azure resources and resource groups.
-
@azure/arm-storage: Supports management of Azure Storage resources, including resource groups and storage accounts.
Adicione as declarações import a seguir:
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient
Client library information:
-
azure-identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
-
azure-storage-blob: Contains the primary classes that you can use to work with Blob Storage data resources.
-
azure-mgmt-resource: Supports management of Azure resources and resource groups.
-
azure-mgmt-storage: Supports management of Azure Storage resources, including resource groups and storage accounts.
Register the Storage resource provider with a subscription
A resource provider must be registered with your Azure subscription before you can work with it. This step only needs to be done once per subscription, and only applies if the resource provider Microsoft.Storage is not currently registered with your subscription.
You can register the Storage resource provider, or check the registration status, using Azure portal, Azure CLI, or Azure PowerShell.
You can also use the Azure management libraries to check the registration status and register the Storage resource provider, as shown in the following examples:
public static async Task RegisterSRPInSubscription(SubscriptionResource subscription)
{
ResourceProviderResource resourceProvider =
await subscription.GetResourceProviderAsync("Microsoft.Storage");
// Check the registration state of the resource provider and register, if needed
if (resourceProvider.Data.RegistrationState == "NotRegistered")
resourceProvider.Register();
}
public void RegisterSRPInSubscription(AzureResourceManager armClient) {
// Check the registration state of the resource provider and register, if needed
if (armClient.providers().getByName("Microsoft.Storage").registrationState() == "NotRegistered")
armClient.providers().register("Microsoft.Storage");
}
async function registerSRPInSubscription(resourceMgmtClient /*: ResourceManagementClient*/) {
// Check the registration state of the resource provider and register, if needed
if (resourceMgmtClient.providers.get("Microsoft.Storage").registrationState == "NotRegistered")
resourceMgmtClient.providers.register("Microsoft.Storage");
}
def register_srp_in_subscription(self, resource_mgmt_client: ResourceManagementClient):
if (resource_mgmt_client.providers.get("Microsoft.Storage").registration_state == "NotRegistered"):
resource_mgmt_client.providers.register("Microsoft.Storage")
Observação
To perform the register operation, you'll need permissions for the following Azure RBAC action: Microsoft.Storage/register/action. This permission is included in the Contributor and Owner roles.
Query for the Blob Storage endpoint
To retrieve the Blob Storage endpoint for a given storage account, we need to get the storage account properties by calling the Get Properties operation. The following code samples use both the data access and management libraries to get a Blob Storage endpoint for a specified storage account:
To get the properties for a specified storage account, use the following method from a StorageAccountCollection object:
This method returns a StorageAccountResource object, which represents the storage account.
public static async Task<Uri> GetBlobServiceEndpoint(
string storageAccountName,
TokenCredential credential)
{
// TODO: replace with your subscription ID and resource group name
// You can locate your subscription ID on the Subscriptions blade
// of the Azure portal (https://portal.azure.com)
const string subscriptionId = "<subscription-id>";
const string rgName = "<resource-group-name>";
ArmClient armClient = new(credential);
// Create a resource identifier, then get the subscription resource
ResourceIdentifier resourceIdentifier = new($"/subscriptions/{subscriptionId}");
SubscriptionResource subscription = armClient.GetSubscriptionResource(resourceIdentifier);
// Get a resource group
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(rgName);
// Get a collection of storage account resources
StorageAccountCollection accountCollection = resourceGroup.GetStorageAccounts();
// Get the properties for the specified storage account
StorageAccountResource storageAccount = await accountCollection.GetAsync(storageAccountName);
// Return the primary endpoint for the blob service
return storageAccount.Data.PrimaryEndpoints.BlobUri;
}
To get the properties for a specified storage account, use the following method from an AzureResourceManager object:
This method returns a StorageAccount interface, which is an immutable client-side representation of the storage account.
public String GetBlobServiceEndpoint(String saName, DefaultAzureCredential credential) {
String subscriptionID = "<subscription-id>";
String rgName = "<resource-group-name>";
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
AzureResourceManager azureResourceManager = AzureResourceManager
.configure()
.authenticate(credential, profile)
.withSubscription(subscriptionID);
StorageAccount storageAccount = azureResourceManager.storageAccounts()
.getByResourceGroup(rgName, saName);
String endpoint = storageAccount.endPoints().primary().blob();
return endpoint;
}
To get the properties for a specified storage account, use the following method from a StorageManagementClient object:
This method returns a Promise<StorageAccountsGetPropertiesResponse>, which represents the storage account.
async function getBlobServiceEndpoint(saName, credential) {
const subscriptionId = "<subscription-id>";
const rgName = "<resource-group-name>";
const storageMgmtClient = new StorageManagementClient(
credential,
subscriptionId
);
// Get the properties for the specified storage account
const storageAccount = await storageMgmtClient.storageAccounts.getProperties(
rgName,
saName
);
// Get the primary endpoint for the blob service
const endpoint = storageAccount.primaryEndpoints.blob;
return endpoint;
}
To get the properties for a specified storage account, use the following method from a StorageManagementClient object:
This method returns a StorageAccount object, which represents the storage account.
def get_blob_service_endpoint(self, storage_account_name, credential: DefaultAzureCredential) -> str:
subscription_id = "<subscription-id>"
rg_name = "<resource-group-name>"
storage_mgmt_client = StorageManagementClient(
credential=credential,
subscription_id=subscription_id
)
# Get the properties for the specified storage account
storage_account = storage_mgmt_client.storage_accounts.get_properties(
resource_group_name=rg_name,
account_name=storage_account_name
)
# Get blob service endpoint
endpoint = storage_account.primary_endpoints.blob
return endpoint
Create a client object using the endpoint
Once you have the Blob Storage endpoint for a storage account, you can instantiate a client object to work with data resources. The following code sample creates a BlobServiceClient object using the endpoint we retrieved in the earlier example:
// Create an instance of DefaultAzureCredential for authorization
TokenCredential credential = new DefaultAzureCredential();
// TODO: replace with your storage account name
string storageAccountName = "<storage-account-name>";
// Call out to our function that retrieves the blob service endpoint for the given storage account
Uri blobURI = await AccountProperties.GetBlobServiceEndpoint(storageAccountName, credential);
Console.WriteLine($"URI: {blobURI}");
// Now that we know the endpoint, create the client object
BlobServiceClient blobServiceClient = new(blobURI, credential);
// Do something with the storage account or its resources ...
String saName = "<storage-account-name>";
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
AccountProperties accountProps = new AccountProperties();
String blobEndpoint = accountProps.GetBlobServiceEndpoint(saName, credential);
System.out.printf("URI: %s", blobEndpoint);
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
.endpoint(blobEndpoint)
.credential(credential)
.buildClient();
// Do something with the storage account or its resources ...
// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential.
// See https://aka.ms/azsdk/js/identity/examples for more details.
const saName = "<storage-account-name>";
const credential = new DefaultAzureCredential();
// Call out to our function that retrieves the blob service endpoint for a storage account
const endpoint = await getBlobServiceEndpoint(saName, credential)
console.log(endpoint);
// Now that we know the endpoint, create the client object
const blobServiceClient = new BlobServiceClient(
endpoint,
credential);
// Do something with the storage account or its resources ...
storage_account_name = "<storage-account-name>"
credential = DefaultAzureCredential()
sample = BlobEndpointSample()
# Call out to our function that retrieves the blob service endpoint for a storage account
endpoint = sample.get_blob_service_endpoint(storage_account_name, credential)
print(f"URL: {endpoint}")
# Now that we know the endpoint, create the client object
blob_service_client = BlobServiceClient(account_url=endpoint, credential=credential)
# Do something with the storage account or its resources ...
Próximos passos
View the full code samples (GitHub):
To learn more about creating client objects, see Create and manage client objects that interact with data resources.