且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中使用SAS访问Azure Blob

更新时间:2023-02-08 23:27:47

使用帐户密钥时,需要上面使用的代码.这是您需要计算并在请求中包含Authorization标头的时候.如果您使用的是Shared Access Signature (SAS)令牌,则无需执行所有操作,因为SAS令牌已包含授权信息.

The code you're using above is needed when you're using an account key. This is when you would need to compute and include Authorization header in your request. If you're using a Shared Access Signature (SAS) token, you don't need to do all of this because SAS token already includes authorization information.

假设您的SAS令牌有效并且包含上传文件的适当权限,您的代码将变得非常简单.请在下面查看修改后的代码:

Assuming your SAS Token is valid and contain appropriate permissions to upload a file, your code becomes quite simple. Please see modified code below:

void UploadFileToAzureBlobStorage(string content, string fileName)
{
    string sasToken = "SAS Key";
    string storageAccount = "Storage Account name";
    string containerName = "Container Name";
    string blobName = fileName;

    string method = "PUT";
    string sampleContent = content;
    int contentLength = Encoding.UTF8.GetByteCount(sampleContent);

    string requestUri = $"https://{storageAccount}.blob.core.windows.net/{containerName}/{blobName}?{sasToken}";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
    request.Method = method;
    request.ContentType = "text/plain; charset=UTF-8";
    request.ContentLength = contentLength;
    request.Headers.Add("x-ms-blob-type", "BlockBlob");

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
    }

    using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
    {
        if (resp.StatusCode == HttpStatusCode.OK)
        { }
    }
}