简体   繁体   English

以编程方式获取Azure存储帐户属性

[英]Programmatically get Azure storage account properties

I wrote in my C# web application a method that deletes old blobs from Azure storage account. 我在C#web应用程序中编写了一个从Azure存储帐户中删除旧blob的方法。

This is my code: 这是我的代码:

public void CleanupIotHubExpiredBlobs()
{
   const string StorageAccountName = "storageName";
   const string StorageAccountKey = "XXXXXXXXXX";
   const string StorageContainerName = "outputblob";
   string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, StorageAccountKey);

   // Retrieve storage account from connection string.
   CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
   // Create the blob client.
   CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
   // select container in which to look for old blobs.
   CloudBlobContainer container = blobClient.GetContainerReference(StorageContainerName);

   // set up Blob access condition option which will filter all the blobs which are not modified for X (this.m_CleanupExpirationNumOfDays) amount of days
   IEnumerable<IListBlobItem> blobs = container.ListBlobs("", true);

  foreach (IListBlobItem blob in blobs)
  {
    CloudBlockBlob cloudBlob = blob as CloudBlockBlob;
    Console.WriteLine(cloudBlob.Properties);
    cloudBlob.DeleteIfExists(DeleteSnapshotsOption.None, AccessCondition.GenerateIfNotModifiedSinceCondition(DateTime.Now.AddDays(-1 * 0.04)), null, null);
  }

   LogMessageToFile("Remove old blobs from storage account");
}

as you can see, In order to achieve that The method has to receive StorageAccountName and StorageAccountKey parameters. 如您所见,为了实现该方法必须接收StorageAccountName和StorageAccountKey参数。

One way to do that is by configuring these parameters in a config file for the app to use, But this means the user has to manually insert these two parameters to the config file. 一种方法是在配置文件中配置这些参数供应用程序使用,但这意味着用户必须手动将这两个参数插入配置文件。

My question is: is there a way to programmatically retrieve at least one of these parameters in my code, so that at least the user will have to insert only one parameters and not two? 我的问题是:有没有办法在我的代码中以编程方式检索这些参数中的至少一个,这样至少用户只需插入一个参数而不是两个参数? my goal is to make the user's life easier. 我的目标是让用户的生活更轻松。

My question is: is there a way to programmatically retrieve at least one of these parameters in my code, so that at least the user will have to insert only one parameters and not two? 我的问题是:有没有办法在我的代码中以编程方式检索这些参数中的至少一个,这样至少用户只需插入一个参数而不是两个参数? my goal is to make the user's life easier. 我的目标是让用户的生活更轻松。

According to your description, I suggest you could use azure rest api to get the storage account key by using account name. 根据您的描述,我建议您使用azure rest api通过帐户名获取存储帐户密钥。

Besides, we could also use rest api to list all the rescourse group's storage account name, but it still need to send the rescourse group name as parameter to the azure management url. 此外,我们还可以使用rest api列出所有rescourse组的存储帐户名称,但仍需要将rescourse组名称作为参数发送到azure管理URL。

You could send the request to the azure management as below url: 您可以将请求发送到azure管理,如下所示:

POST: https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resrouceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/listKeys?api-version=2016-01-01
Authorization: Bearer {token}

More details, you could refer to below codes: 更多细节,您可以参考以下代码:

Notice: Using this way, you need firstly create an Azure Active Directory application and service principal. 注意:使用这种方式,首先需要创建Azure Active Directory应用程序和服务主体。 After you generate the service principal, you could get the applicationid,access key and talentid. 生成服务主体后,您可以获取applicationid,访问密钥和talentid。 More details, you could refer to this article . 更多细节,您可以参考这篇文章

Code: 码:

    string tenantId = " ";
    string clientId = " ";
    string clientSecret = " ";
    string subscription = " ";
    string resourcegroup = "BrandoSecondTest";
    string accountname = "brandofirststorage";
    string authContextURL = "https://login.windows.net/" + tenantId;
    var authenticationContext = new AuthenticationContext(authContextURL);
    var credential = new ClientCredential(clientId, clientSecret);
    var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
    if (result == null)
    {
        throw new InvalidOperationException("Failed to obtain the JWT token");
    }
    string token = result.AccessToken;
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Storage/storageAccounts/{2}/listKeys?api-version=2016-01-01", subscription, resourcegroup, accountname));
    request.Method = "POST";
    request.Headers["Authorization"] = "Bearer " + token;
    request.ContentType = "application/json";
    request.ContentLength = 0;


    //Get the response
    var httpResponse = (HttpWebResponse)request.GetResponse();

    using (System.IO.StreamReader r = new System.IO.StreamReader(httpResponse.GetResponseStream()))
    {
        string jsonResponse = r.ReadToEnd();

        Console.WriteLine(jsonResponse);
    }

Result: 结果: 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM