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

.NET中Cloud Storage签名URL自定义下载文件名问题

Cloud Storage签名URL自定义下载文件名解决方案

问题根源

你用UrlSigner生成签名URL时,直接手动加response-content-disposition参数不生效,是因为UrlSigner需要把所有请求参数纳入签名流程,必须通过官方API配置这些参数,而不是自己拼接URL。

实现步骤

1. 配置GetObjectRequest

创建GetObjectRequest实例,指定桶名、文件键,同时设置ResponseContentDisposition属性,值为attachment; filename="你的友好文件名.ext"。如果文件名包含中文或特殊字符,采用RFC 5987编码格式:attachment; filename*=UTF-8''{编码后的文件名},编码可通过Uri.EscapeDataString()方法处理。

2. 签名配置好的请求

调用UrlSigner的Sign或SignAsync方法,传入这个配置完成的GetObjectRequest,而非单独传入桶名和文件键。

示例代码

using Google.Cloud.Storage.V1;
using System;

public static string GetSignedDownloadUrl(string bucketName, string objectKey, string friendlyName)
{
    var signer = UrlSigner.FromServiceAccountPath("service-account-key.json");
    
    // 处理含特殊字符的文件名
    var encodedFilename = Uri.EscapeDataString(friendlyName);
    var disposition = $"attachment; filename*=UTF-8''{encodedFilename}";

    var request = new GetObjectRequest
    {
        Bucket = bucketName,
        Object = objectKey,
        ResponseContentDisposition = disposition
    };

    // 生成有效期1小时的V4签名URL
    return signer.Sign(request, TimeSpan.FromHours(1), UrlSigner.SignatureVersion.V4);
}

注意事项

  • 禁止手动在生成的URL后拼接response-content-disposition参数,因为签名URL会验证所有参数,未被纳入签名流程的参数会被Cloud Storage拒绝访问。
  • 确认使用的Google.Cloud.Storage.V1 3.5.0版本支持GetObjectRequest的ResponseContentDisposition属性(3.x版本均支持该属性)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:20:41