Todos os produtos
Search
Central de documentação

Object Storage Service:Inicialização (C# SDK V1)

Última atualização: Jul 03, 2026

OssClient é o cliente C# para Object Storage Service (OSS). Use-o para gerenciar recursos do OSS, como buckets e objetos.

Criar um OssClient

Crie uma instância de OssClient usando um dos métodos a seguir.

Assinatura V4 (Recomendado)

O algoritmo de assinatura V4 oferece maior segurança. Para inicializar o cliente com essa versão, especifique o Endpoint e o ID da região geral da Alibaba Cloud. O ID da Região identifica a região da solicitação, por exemplo, cn-hangzhou. Declare também SignVersion.V4. As assinaturas V4 são compatíveis com o OSS .NET SDK 2.14.0 e versões posteriores.

O exemplo a seguir mostra como criar uma instância de OssClient com assinatura V4 e nome de domínio do OSS. Adapte este exemplo para outros cenários, como uso de nome de domínio personalizado ou Security Token Service (STS).

using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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 Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

// Specify the Region ID for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);

Assinatura V1 (Não recomendado)

Importante

Usar um endpoint do OSS para criar uma instância de OssClient

O código a seguir mostra como criar uma instância de OssClient usando um nome de domínio do OSS.

using Aliyun.OSS;
// 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 Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
  
// Create an OssClient instance.
var ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);                    

Usar um nome de domínio personalizado para criar uma instância de OSSClient

O código a seguir mostra como criar uma instância de OssClient usando um nome de domínio personalizado.

Importante

Ao usar um nome de domínio personalizado, o método ossClient.listBuckets não é suportado.

using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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 custom domain name.
const string endpoint = "yourDomain";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Enable CNAME. CNAME is the procedure to attach a custom domain name to a bucket.
conf.IsCname = true;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);                    

Criar um OssClient com STS

O código a seguir mostra como criar uma instância de OssClient usando o Security Token Service (STS).

using Aliyun.OSS;
// Before you run this sample code, make sure that you have used the temporary AccessKey pair obtained from STS to set the YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET environment variables.
var accessKeyId = Environment.GetEnvironmentVariable("YOUR_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("YOUR_ACCESS_KEY_SECRET");
// The security token obtained from STS.
const string  securityToken = "yourSecurityToken";
// Specify the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

// Create an OssClient instance.
var ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret, securityToken);

Configurar o OssClient

ClientConfiguration é a classe de configuração do OssClient. Use essa classe para definir parâmetros como proxy, tempo limite de conexão e número máximo de conexões. Configure os seguintes parâmetros:

Parâmetro

Descrição

Valor padrão

ConnectionLimit

Número máximo de conexões simultâneas.

512

MaxErrorRetry

Número máximo de novas tentativas para uma solicitação com falha.

3

ConnectionTimeout

Tempo limite de conexão, em milissegundos.

-1 (sem tempo limite)

EnableMD5Check

Define se a validação MD5 deve ser ativada para uploads ou downloads de dados.

  • true: Ativa a validação MD5.

  • false: Desativa a validação MD5.

Importante

A validação MD5 causa sobrecarga de desempenho.

false

IsCname

Indica se o Endpoint suporta CNAME. O CNAME vincula um nome de domínio personalizado a um bucket.

false

ProgressUpdateInterval

Intervalo de atualização da barra de progresso, em bytes.

8096

ProxyHost

Servidor proxy. Exemplo: example.aliyundoc.com.

Nenhum

ProxyPort

Porta do proxy. Exemplo: 3128 ou 8080.

Nenhum

ProxyUserName

Nome de usuário do serviço de proxy. Este parâmetro é opcional.

Nenhum

ProxyPassword

Senha do serviço de proxy. Este parâmetro é opcional.

Nenhum

O código a seguir mostra como configurar o OssClient.

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

var conf = new ClientConfiguration();
// Set the maximum number of concurrent connections.
ClientConfiguration.ConnectionLimit = 512;
// Set the maximum number of retries for a failed request.
conf.MaxErrorRetry = 3;
// Set the connection timeout period.
conf.ConnectionTimeout = 300;
// Enable MD5 validation.
conf.EnableMD5Check = true;
// Set the proxy server.
conf.ProxyHost = "example.aliyundoc.com";
// Set the proxy port.
conf.ProxyPort = 3128;
// Set the username for the proxy.
conf.ProxyUserName = "user";
// Set the password for the proxy.
conf.ProxyPassword = "password";

var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);