O OssClient é o cliente C# do Object Storage Service (OSS). Use-o para gerencie recursos do OSS, como buckets e objetos.
Crie um OssClient
Crie uma instância do OssClient usando um dos métodos a seguir.
V4 signature (Recommended)
O algoritmo de assinatura V4 é mais seguro. Para inicializar o cliente com assinatura V4, especifique o endpoint e o ID de região genérico da Alibaba Cloud. O ID de região identifica a região da solicitação — por exemplo, cn-hangzhou. Também é necessário declarar 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 demonstra como crie uma instância do OssClient com assinatura V4 e um nome de domínio do OSS. Adapte este exemplo a outros cenários, como o uso de um nome de domínio personalizado ou do 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);
V1 signature (Not recommended)
A partir de 1º de março de 2025, o Alibaba Cloud Object Storage Service (OSS) deixou de oferecer a assinatura V1 para novos usuários (ou seja, novos UIDs). A partir de 1º de setembro de 2025, o OSS descontinuará a atualização e a manutenção da assinatura V1 e não oferecerá mais a assinatura V1 para novos buckets de armazenamento de objetos. Migre para a assinatura V4 o mais rápido possível para evitar interrupções no service. Para mais informações, consulte Comunicado.
Use an OSS endpoint to create an OssClient instance
O código a seguir mostra como crie uma instância do 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);
Use a custom domain name to create an OSSClient instance
O código a seguir mostra como crie uma instância do OssClient usando um nome de domínio personalizado.
Ao usar um nome de domínio personalizado, o método ossClient.listBuckets não é compatível.
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);
Create an OssClient with STS
O código a seguir mostra como crie uma instância do 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);
Configure o OssClient
ClientConfiguration é a classe de configuração do OssClient. Use essa classe para defina parâmetros como proxy, tempo limite de conexão e número máximo de conexões. Veja os parâmetros configuráveis a seguir:
|
Parâmetro |
Descrição |
Valor padrão |
|
ConnectionLimit |
Número máximo de conexões simultâneas. |
512 |
|
MaxErrorRetry |
Número máximo de tentativas para uma solicitação com falha. |
3 |
|
ConnectionTimeout |
Tempo limite de conexão, em milissegundos. |
-1 (sem tempo limite) |
|
EnableMD5Check |
Indica se a validação MD5 está ativada para uploads ou downloads de dados.
Importante
A validação MD5 gera alguma sobrecarga de desempenho. |
false |
|
IsCname |
Indica se o endpoint oferece suporte a CNAME. O CNAME serve para vincular um nome de domínio personalizado a um bucket. |
false |
|
ProgressUpdateInterval |
Intervalo de atualize da barra de progresso, em bytes. |
8096 |
|
ProxyHost |
Servidor proxy. Por exemplo, |
Nenhum |
|
ProxyPort |
Porta do proxy. Por exemplo, |
Nenhum |
|
ProxyUserName |
Nome de usuário do service de proxy. Este parâmetro é opcional. |
Nenhum |
|
ProxyPassword |
Senha do service de proxy. Este parâmetro é opcional. |
Nenhum |
O código a seguir mostra como configure 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);