我是 Azure 的新手,我想为 blob 项(word 文件)生成 SAS 访问令牌,包括读取和写入该文件。
我的场景是:用户应该提交他们的数据,然后我应该以字符串数组的形式接收这些数据,并将其放入存储在 Azure blob 存储中的表单中。
我已经实现了使用用户数据更新表单的方法,因为我有一段代码可以生成访问令牌,还有一段代码可以读取和写入文件,但它不起作用对我来说!
这是我的代码:
async static Task<Uri> GetUserDelegationSasBlob(BlobClient blobClient)
{
BlobServiceClient blobServiceClient =
blobClient.GetParentBlobContainerClient().GetParentBlobServiceClient();
// Get a user delegation key
Azure.Storage.Blobs.Models.UserDelegationKey userDelegationKey =
await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddDays(7));
// Create a SAS token
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = blobClient.BlobContainerName,
BlobName = blobClient.Name,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddDays(7)
};
// Specify read and write permissions for the SAS.
sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);
// Add the SAS token to the blob URI.
BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
{
// Specify the user delegation key.
Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,
blobServiceClient.AccountName)
};
Console.WriteLine("Blob user delegation SAS URI: {0}", blobUriBuilder);
Console.WriteLine();
return blobUriBuilder.ToUri();
}
static async Task ReadBlobWithSasAsync(Uri sasUri)
{
//Read file content
public static void Run(Stream myBlob, string fileContent)
{
StreamReader contentReader = new StreamReader(myBlob);
string sampleContent = contentReader.ReadToEnd();
char[] spearator = { ' ' };
string[] content = sampleContent.Split(spearator);
reader.FillForm(content);
}
// Create a blob client object for blob operations.
BlobClient blobClient = new BlobClient(sasUri, null);
// Download and read the contents of the blob.
try
{
Console.WriteLine("Blob contents:");
// Download blob contents to a stream and read the stream.
BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync();
using (StreamReader reader = new StreamReader(blobDownloadInfo.Content, true))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.WriteLine();
Console.WriteLine("Read operation succeeded for SAS {0}", sasUri);
Console.WriteLine();
}
catch (RequestFailedException e)
{
// Check for a 403 (Forbidden) error. If the SAS is invalid,
// Azure Storage returns this error.
if (e.Status == 403)
{
Console.WriteLine("Read operation failed for SAS {0}", sasUri);
Console.WriteLine("Additional error information: " + e.Message);
Console.WriteLine();
}
else
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
}