You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#生成Azure Blob SAS URI时签名格式错误问题求助

问题根源与修复方案

你的代码存在两个关键错误,直接导致了SAS签名验证失败:

  1. 端点类型混淆:你使用了Azure文件存储的端点(file.core.usgovcloudapi.net)初始化BlobServiceClient,但Blob服务的专属端点应为blob.core.usgovcloudapi.net。文件存储与Blob存储是独立的Azure服务,混用端点会让签名生成逻辑完全不匹配。

  2. 权限枚举错误:在BlobSasBuilder中错误使用了BlobAccountSasPermissions(用于账户级SAS的权限枚举),Blob级SAS必须使用BlobSasPermissions。


修正后的完整代码

static void Main(string[] args)
{
    StorageSharedKeyCredential keyCredential = new StorageSharedKeyCredential(accountName, accountKey);
    // 修正:使用Blob存储专用端点
    BlobServiceClient serviceClient = new BlobServiceClient(new Uri($"https://{accountName}.blob.core.usgovcloudapi.net"), keyCredential);

    BlobClient blobClient = serviceClient.GetBlobContainerClient("account-data").GetBlobClient("ADImport.csv");
    Uri sasURL = CreateServiceASBlob(blobClient);

    Console.WriteLine(sasURL);
    Console.ReadLine();
}

public static Uri CreateServiceASBlob(BlobClient blobClient)
{
    if (blobClient.CanGenerateSasUri)
    {
        BlobSasBuilder sasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
            BlobName = blobClient.Name,
            Resource = "b", // "b"代表Blob资源类型,配置正确
            StartsOn = DateTimeOffset.UtcNow.AddHours(-1),
            ExpiresOn = DateTimeOffset.UtcNow.AddDays(1)
        };
        
        // 修正:使用Blob级权限枚举
        sasBuilder.SetPermissions(BlobSasPermissions.Read);

        return blobClient.GenerateSasUri(sasBuilder);
    }

    return null;
}

额外验证要点

  • 确认accountName和accountKey属于Blob存储账户,而非文件存储账户。
  • 生成SAS后直接在浏览器访问URI,正常应触发文件下载;若仍失败,检查Blob是否确实存在(容器的公共访问设置不影响SAS有效性)。

内容的提问来源于stack exchange,提问作者HastingsN2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:47:04