我在C#web应用程序中编写了一个从Azure存储帐户中删除旧blob的方法。
这是我的代码:
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");
}
正如您所看到的,为了实现该方法,必须接收StorageAccountName和StorageAccountKey参数。
一种方法是在配置文件中配置这些参数供应用程序使用,但这意味着用户必须手动将这两个参数插入配置文件。
我的问题是: 有没有办法在我的代码中以编程方式检索这些参数中的至少一个,这样至少用户只需要插入一个参数,而不是两个?我的目标是让用户的生活更轻松。
答案 0 :(得分:2)
我的问题是:有没有办法在我的代码中以编程方式检索这些参数中的至少一个,这样至少用户只需插入一个参数而不是两个参数?我的目标是让用户的生活更轻松。
根据您的说明,我建议您使用azure rest api来使用帐户名称来获取存储帐户密钥。
此外,我们还可以使用rest api列出所有rescourse组的存储帐户名,但仍需要将rescourse组名作为参数发送到azure管理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}
更多细节,您可以参考以下代码:
注意:使用这种方式,首先需要创建Azure Active Directory应用程序和服务主体。生成服务主体后,您可以获取applicationid,访问密钥和talentid。更多细节,您可以参考此article。
代码:
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);
}