Todos os produtos
Search
Central de documentação

Object Storage Service:Pay-by-requester (OSS SDK for C# 1.0)

Última atualização: Sep 24, 2026

Quando o pagamento pelo solicitante está ativado em um bucket do Object Storage Service (OSS), o solicitante paga as taxas de requisição e tráfego em vez do proprietário do bucket. O proprietário do bucket paga apenas as taxas de armazenamento. Você pode ativar o pagamento pelo solicitante em um bucket para compartilhar dados sem arcar com os custos de requisição e tráfego gerados pelo acesso ao seu bucket.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Initialization (C# SDK V1).

  • Para ativar o pagamento pelo solicitante, você precisa ter a permissão oss:PutBucketRequestPayment. Para consultar as configurações de pagamento pelo solicitante, você precisa ter a permissão oss:GetBucketRequestPayment. Para mais informações, consulte Grant a custom policy.

Ative o pagamento pelo solicitante para um bucket

O código a seguir mostra como ativar o pagamento pelo solicitante para um bucket:

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
            
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
            
// Use the signature algorithm V4.
 conf.SignatureVersion = SignatureVersion.V4;
            
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
try
{
    // Enable pay-by-requester for the bucket. 
    var request = new SetBucketRequestPaymentRequest(bucketName, RequestPayer.Requester);
    client.SetBucketRequestPayment(request);
    Console.WriteLine("Set bucket:{0} RequestPayment succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}

Consultar as configurações de pagamento pelo solicitante

O código a seguir mostra como consultar as configurações de pagamento pelo solicitante de um bucket:

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
            
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
            
// Use the signature algorithm V4.
 conf.SignatureVersion = SignatureVersion.V4;
            
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
try
{
    // Query the pay-by-requester configurations of the bucket. 
    var result = client.GetBucketRequestPayment(bucketName);
    Console.WriteLine("Set bucket:{0} RequestPayment succeeded; RequestPayment: {1}", bucketName, result.Payer);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}            

Especifique que terceiros sejam cobrados ao acessar objetos

Se você especificar a cobrança de terceiros no acesso a objetos em um bucket, os solicitantes deverão incluir o cabeçalho x-oss-request-payer:requester nas requisições HTTP para realizar operações em seus objetos. A omissão desse cabeçalho gera um erro.

O código a seguir mostra como especificar que terceiros sejam cobrados ao acessar objetos por meio das operações PutObject, GetObject e DeleteObject. Você também pode aplicar esse método para cobrar terceiros em operações de leitura e gravação de objetos ao chamar outras operações de API de forma semelhante.

using System;
using System.IO;
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace Samples
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
            var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
            var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
            var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
            // Specify the name of the bucket. Example: examplebucket. 
            var bucketName = "examplebucket";
            var objectName = "example.txt";
            var objectContent = "More than just cloud.";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            const string region = "cn-hangzhou";
            // Create a ClientConfiguration instance and modify parameters as required.
            var conf = new ClientConfiguration();
            // Use the signature algorithm V4.
            conf.SignatureVersion = SignatureVersion.V4;
            
            // Create an OSSClient instance.
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);

            try
            {
                byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
                MemoryStream requestContent = new MemoryStream(binaryData);
                // Specify the payer when a third party calls the PutObject operation. 
                var putRequest = new PutObjectRequest(bucketName, objectName, requestContent);
                putRequest.RequestPayer = RequestPayer.Requester;
                var result = client.PutObject(putRequest);

                // Specify the payer when a third party calls the GetObject operation. 
                var getRequest = new GetObjectRequest(bucketName, objectName);
                getRequest.RequestPayer = RequestPayer.Requester;
                var getResult = client.GetObject(getRequest);

                // Specify the payer when a third party calls the DeleteObject operation. 
                var delRequest = new DeleteObjectRequest(bucketName, objectName);
                delRequest.RequestPayer = RequestPayer.Requester;
                client.DeleteObject(delRequest);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
    }
}

Referências

  • Para mais informações sobre a operação de API usada para ativar o pagamento pelo solicitante, consulte PutBucketRequestPayment.

  • Para mais detalhes sobre a operação de API usada para consultar as configurações de pagamento pelo solicitante de um bucket, consulte GetBucketRequestPayment.