Todos los productos
Search
Centro de documentos

Object Storage Service:Inicialización (C# SDK V1)

Última actualización: Sep 03, 2026

OssClient es el cliente de C# para Object Storage Service (OSS). Úselo para gestionar recursos de OSS, como buckets y objetos.

Crear un OssClient

Cree una instancia de OssClient mediante uno de los siguientes métodos.

Firma V4 (recomendada)

El algoritmo de firma V4 ofrece mayor seguridad. Para inicializar el cliente con una firma V4, especifique el endpoint y el ID de región de Alibaba Cloud de uso general. El ID de región identifica la región de la solicitud; por ejemplo, cn-hangzhou. También debe declarar SignVersion.V4. Las firmas V4 son compatibles con OSS .NET SDK 2.14.0 y versiones posteriores.

En el siguiente ejemplo se muestra cómo crear una instancia de OssClient con una firma V4 y un nombre de dominio de OSS. Adapte este ejemplo a otros escenarios, como el uso de un nombre de dominio personalizado o 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);

Firma V1 (no recomendada)

Importante

Uso de un endpoint de OSS para crear una instancia de OssClient

En el siguiente código se muestra cómo crear una instancia de OssClient mediante un nombre de dominio de 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);                    

Uso de un nombre de dominio personalizado para crear una instancia de OSSClient

En el siguiente código se muestra cómo crear una instancia de OssClient mediante un nombre de dominio personalizado.

Importante

Si utiliza un nombre de dominio personalizado, el método ossClient.listBuckets no es compatible.

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);                    

Creación de un OssClient con STS

En el siguiente código se muestra cómo crear una instancia de OssClient mediante 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 OssClient

ClientConfiguration es la clase de configuración para OssClient. Use esta clase para configurar parámetros como el proxy, el tiempo de espera de conexión y el número máximo de conexiones. Puede configurar los siguientes parámetros:

Parámetro

Descripción

Valor predeterminado

ConnectionLimit

Número máximo de conexiones simultáneas.

512

MaxErrorRetry

Número máximo de reintentos para una solicitud con errores.

3

ConnectionTimeout

Tiempo de espera de conexión, en milisegundos.

-1 (sin tiempo de espera)

EnableMD5Check

Indica si se habilita la validación MD5 para cargas o descargas de datos.

  • true: habilita la validación MD5.

  • false: deshabilita la validación MD5.

Importante

La validación MD5 genera cierta sobrecarga de rendimiento.

false

IsCname

Indica si el endpoint admite CNAME. CNAME se usa para vincular un nombre de dominio personalizado a un bucket.

false

ProgressUpdateInterval

Intervalo de actualización de la barra de progreso, en bytes.

8096

ProxyHost

Servidor proxy. Por ejemplo, example.aliyundoc.com.

Ninguna

ProxyPort

Puerto del proxy. Por ejemplo, 3128 o 8080.

Ninguna

ProxyUserName

Nombre de usuario para el servicio de proxy. Este parámetro es opcional.

Ninguna

ProxyPassword

Contraseña para el servicio de proxy. Este parámetro es opcional.

Ninguna

En el siguiente código se muestra cómo configurar 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);