C#调用Azure Blob Storage REST API删除Blob返回403错误求助
问题根因
你遇到的403错误核心是签名字符串的Content-Length字段取值不符合Azure Shared Key规范:
- PUT上传Blob请求带有请求体,
request.ContentLength会被自动赋值为正整数,拼接后的签名和服务端计算结果一致,所以请求正常 - DELETE请求没有请求体,
HttpWebRequest的ContentLength默认值为-1,而Azure要求无请求体的请求在签名时Content-Length对应的位置必须为空字符串,你把-1拼接进签名字符串后,签名校验失败,直接返回403。
修复方案
- 首先修改
AuthorizationHeader方法中的签名字符串拼接逻辑,对Content-Length做兼容处理:
private string AuthorizationHeader(string method, HttpWebRequest request, string containerName, string blobName) { string urlResource = $"/{_accountName}/{containerName}/{blobName}"; // 新增Content-Length兼容逻辑:无请求体时用空字符串替代-1 string contentLength = request.ContentLength >= 0 ? request.ContentLength.ToString() : string.Empty; string stringToSign = $"{method}\n\n\n{contentLength}\n\n{request.ContentType}\n\n\n\n\n\n\n{GetCanonicalizedHeaders(request)}{GetCanonicalizedResource(request.RequestUri, _accountName)}"; HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(_accountKey)); string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); return string.Format("{0} {1}:{2}", "SharedKey", _accountName, signature); }
- 可以在构造DELETE请求时主动设置Content-Length为0,双重保险避免签名错误:
// 在DeleteBlob方法中设置请求方法后新增一行 request.Method = method; request.ContentLength = 0; // 后续头设置逻辑保持不变
- 额外清理建议:你代码中存在两个生成授权头的方法
AuthorizationHeader和GetAuthorizationHeader,后者使用的是简化版SharedKeyLite签名规则,当前逻辑调用的是前者无问题,没用的冗余方法建议删除避免后续误调用。
如果修改后仍有错误,可以查看403响应的返回正文,Azure会在错误信息里明确给出服务端期望的签名字符串,对比你本地生成的字符串就能快速定位剩余差异。
内容的提问来源于stack exchange,提问作者Alberto Avendaño
相关产品推荐
相关产品推荐

