Integração rápida
Integre o OSS SDK para C# V2:
Pré-requisitos
Requer
.NET Framework 4.7.1ou superior.Compatível com
.NET Standard 2.0e versões posteriores.Suporta
.NET 5.0e versões posteriores.-
Para instalar ou atualizar seu ambiente .NET:
Para .NET Framework: Acesse o site oficial da Microsoft para baixar e instalar o .NET Framework 4.7.1 ou superior.
Para .NET Standard: Certifique-se de que uma implementação compatível do .NET esteja instalada (.NET Framework, .NET ou outras plataformas suportadas).
Para .NET: Acesse o site oficial do .NET para baixar e instalar o .NET 5.0 ou superior.
Instalar o SDK
Use a versão mais recente do OSS SDK para C# V2 para garantir que o código de exemplo funcione conforme esperado.
Instalação via NuGet
-
Verificar se o NuGet está instalado:
Certifique-se de que o NuGet esteja instalado no Visual Studio. Caso contrário, abra o Visual Studio Installer em Tools > Get Tools and Features e selecione a carga de trabalho de desenvolvimento para desktop .NET ou desenvolvimento ASP.NET e web.
-
Abrir o projeto:
Crie um novo projeto ou abra um projeto existente no Visual Studio.
-
Abrir o Gerenciador de Pacotes NuGet:
Na barra de menus, escolha Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
-
Pesquisar e instalar o SDK:
Na aba Browse do Gerenciador de Pacotes NuGet, pesquise por
AlibabaCloud.OSS.V2.Selecione
AlibabaCloud.OSS.V2nos resultados. Escolha a versão estável mais recente.Clique em Install e aguarde a conclusão da instalação.
-
Verificar a instalação:
Após a instalação,
AlibabaCloud.OSS.V2aparecerá em References no Solution Explorer.
Instalação importando o projeto
-
Clone o repositório do GitHub:
-
Abra um prompt de comando ou Git Bash e execute o seguinte comando para clonar o repositório:
git clone https://github.com/aliyun/alibabacloud-oss-csharp-sdk-v2.git
-
-
Adicionar o projeto à sua solução:
No Visual Studio, clique com o botão direito na sua solução e escolha Add > Existing Project....
Navegue até o diretório do código-fonte clonado, selecione o arquivo
AlibabaCloud.OSS.V2.csproje clique em Open.
-
Adicionar uma referência de projeto:
Clique com o botão direito no seu projeto e escolha Add > Reference....
Na caixa de diálogo exibida, vá para a aba Projects, localize e selecione o projeto
AlibabaCloud.OSS.V2e clique em OK.
Configurar credenciais de acesso
Configure as credenciais de acesso usando o par AccessKey de um usuário RAM.
No console RAM, crie um usuário RAM com um Permanent AccessKey Pair. Salve o par AccessKey e conceda a permissão
AliyunOSSFullAccessao usuário RAM.-
Configure as variáveis de ambiente usando o par AccessKey do usuário RAM.
Linux
-
Execute os comandos abaixo na interface de linha de comando para anexar as definições das variáveis de ambiente ao arquivo
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Execute o comando a seguir para aplicar a configuração.
source ~/.bashrc -
Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Execute o comando seguinte no terminal para verificar o tipo de shell padrão.
echo $SHELL-
Siga as etapas correspondentes ao seu tipo de shell padrão.
Zsh
-
Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo
~/.zshrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Execute este comando para aplicar a configuração.
source ~/.zshrc -
Execute os comandos abaixo para confirmar que as variáveis de ambiente estão configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Execute os comandos seguintes para anexar as definições das variáveis de ambiente ao arquivo
~/.bash_profile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Execute o comando abaixo para aplicar a configuração.
source ~/.bash_profile -
Execute os comandos a seguir para validar a configuração das variáveis de ambiente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Execute os comandos abaixo no Prompt de Comando.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Execute os comandos a seguir para verificar se as variáveis de ambiente foram definidas.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Execute os comandos seguintes no PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)-
Execute os comandos abaixo para confirmar a configuração das variáveis de ambiente.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Inicializar o cliente
Inicialize um OSSClient com a região e endpoint e execute o código de teste.
using System.Text; // Import the System.Text namespace to process character encoding, such as UTF-8 encoded strings.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var bucket = "your bucket name"; // Required. The name of the destination bucket.
var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var key = "your object key"; // Required. The name of the object to upload. The format is folder/objectName.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// The content of the object to upload. Sample content: a simple string "hello oss!". In actual scenarios, the content can be a file stream or a byte array.
var content = "hello oss!";
// Convert the string to a UTF-8 encoded byte array and then wrap it into a MemoryStream.
// MemoryStream is used to process data streams in memory and is suitable for uploading small files. Use FileStream for large files.
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
// Call the PutObjectAsync method to asynchronously upload the object. You must pass a request object that contains the bucket, key, and body.
// This method uploads the data in bodyStream to the specified key path in the specified bucket.
var result = await client.PutObjectAsync(new OSS.Models.PutObjectRequest()
{
Bucket = bucket, // The name of the destination bucket.
Key = key, // The unique key of the object in the bucket.
Body = bodyStream // The content stream to upload. In this example, it is the string data in memory.
});
// Print the upload result.
Console.WriteLine("PutObject done"); // A message that indicates the operation is complete.
Console.WriteLine($"StatusCode: {result.StatusCode}"); // The HTTP status code.
Console.WriteLine($"RequestId: {result.RequestId}"); // The request ID, which is used for troubleshooting.
Console.WriteLine("Response Headers:"); // The response header information.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Traverse and print all response headers.
Um upload bem-sucedido retorna a seguinte saída:
PutObject done
StatusCode: 200
RequestId: 68808D6D6A91E53037F7AAE9
Response Headers:
Server : AliyunOSS
Date : Wed, 23 Jul 2025 07:21:17 GMT
Connection : keep-alive
x-oss-request-id : 68808D6D6A91E53037F7AAE9
Vary : Origin
ETag : "968205D07B5A124D6ADA9336826C2C90"
x-oss-hash-crc64ecma : 11833582957755287462
x-oss-version-id : CAEQpgEYgYCA3fPQ2MEZIiA2ZmI4NGZkZWQzMWY0ZDZkOTFmMjUxYzRkNGMxODdkZg--
x-oss-server-time : 90
Content-Length : 0
Content-MD5 : loIF0HtaEk1q2pM2gmwskA==
Configurações do cliente
Usar um nome de domínio personalizado
Objetos acessados pelo endpoint padrão do OSS podem não ter pré-visualização nos navegadores. Mapeie um nome de domínio personalizado para acessar o OSS para habilitar pré-visualizações no navegador e aceleração CDN.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = "https://www.example-***.com"; // Required. Your custom domain name. Example: www.example-***.com.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Note that you must set the value to true to enable the CNAME option. Otherwise, you cannot use the custom domain name.
cfg.UseCName = true;
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// Use the created client to perform subsequent operations...
Usar um endpoint interno
Use um endpoint interno para acessar o OSS na mesma região, reduzindo custos de tráfego e aumentando a velocidade de acesso.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com"; // Optional. The internal endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou-internal.aliyuncs.com.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// You can also set cfg.UseInternalEndpoint = true to configure the internal endpoint without the need to specify the internal endpoint.
// cfg.UseInternalEndpoint = true;
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// Use the created client to perform subsequent operations...
Usar um endpoint de aceleração de transferência
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = "https://oss-accelerate.aliyuncs.com"; // Optional. The acceleration endpoint of the region in which the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to 'https://oss-accelerate.aliyuncs.com'.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// You can also set cfg.UseAccelerateEndpoint = true to configure the acceleration endpoint without the need to specify the acceleration endpoint.
// cfg.UseAccelerateEndpoint = true;
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// Use the created client to perform subsequent operations...
Usar um nome de domínio privado
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = "https://service.corp.example.com"; // Required. Your dedicated domain name. For example: https://service.corp.example.com.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// Use the created client to perform subsequent operations...
Usar um endpoint Alibaba Gov Cloud
Configure um OSSClient com um endpoint Gov Cloud:
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-north-2-gov-1"; // Required. The region where the bucket is located. For example, if the bucket is in the China North 2 (Ali Gov 1) region, set the region to cn-north-2-gov-1.
// Required. The internal endpoint of the region in which the bucket is located. For example, if the bucket is in the China North 2 (Ali Gov 1) region, set the endpoint to 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
// To use the HTTP protocol, set the endpoint to 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
var endpoint = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com";
// Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// Use the created client to perform subsequent operations...
Configurações de credenciais de acesso
O OSS suporta diversos métodos de inicialização de credenciais. Escolha um deles com base nos seus requisitos de autenticação.
Usar o par AccessKey de um usuário RAM
Inicialize o provedor de credenciais com um par AccessKey (AccessKey ID e AccessKey secret) de um usuário RAM. Ideal para ambientes seguros que exigem acesso de longo prazo ao OSS sem rotação frequente de credenciais. Requer manutenção manual do par AccessKey.
Uma conta Alibaba Cloud possui permissões totais sobre todos os recursos. Credenciais vazadas expõem seu sistema a riscos significativos de segurança. Utilize o par AccessKey de um usuário RAM com as permissões mínimas necessárias.
O AccessKey ID e o AccessKey secret são exibidos apenas no momento da criação. Salve-os imediatamente — credenciais perdidas não podem ser recuperadas. Criar um par AccessKey.
Variáveis de ambiente
-
Configure as variáveis de ambiente usando o par AccessKey de um usuário RAM.
Após modificar as variáveis de ambiente do sistema, reinicie sua IDE, CLI e outros ambientes de execução para carregar os valores atualizados.
-
Transmita as informações de credenciais usando variáveis de ambiente.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use. var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. // Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables. var cfg = OSS.Configuration.LoadDefault(); // Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider(); // Set the region of the bucket. cfg.Region = region; // If an endpoint is specified, the default endpoint is overwritten. if(endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance based on the configurations. using var client = new OSS.Client(cfg);
Credenciais estáticas
Codifique as credenciais de acesso diretamente definindo o par AccessKey.
Não incorpore credenciais de acesso em aplicações em ambiente de produção. Este método destina-se apenas a testes.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var cfg = OSS.Configuration.LoadDefault();
// Specify the AccessKey ID and AccessKey secret of the RAM user.
var access_key_id = "yourAccessKeyId";
var access_key_secret = "yourAccessKeySecret";
// Create a static credential provider and explicitly set the AccessKey ID and AccessKey secret of the RAM user.
cfg.CredentialsProvider = new OSS.Credentials.StaticCredentialsProvider(access_key_id,access_key_secret);
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
Usar um token STS
Use credenciais de identidade temporárias (AccessKey ID, AccessKey secret e token de segurança) do STS para inicializar o provedor de credenciais para acesso temporário ao OSS. Este método exige manutenção e atualização manual do token STS.
Obtenha rapidamente um token STS chamando AssumeRole.
Obtenha um token STS usando um SDK: Usar um token STS para acessar o OSS.
É necessário especificar um tempo de expiração ao gerar um token STS. O token STS torna-se inválido e não pode ser usado após expirar.
STS Endpoints.
Variáveis de ambiente
-
Defina as variáveis de ambiente usando credenciais de identidade temporárias.
Mac OS X/Linux/Unix
AvisoUse as credenciais de identidade temporárias (AccessKey ID, AccessKey secret e token de segurança) obtidas do STS, e não o par AccessKey de um usuário RAM.
O AccessKey ID obtido do STS começa com
STS., por exemplo,STS.L4aBSCSJVMuKg5U1****.
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>Windows
AvisoUse as credenciais de identidade temporárias (AccessKey ID, AccessKey secret e token de segurança) obtidas do STS, e não o par AccessKey de um usuário RAM.
O AccessKey ID obtido do STS começa com
STS., por exemplo,STS.L4aBSCSJVMuKg5U1****.
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN> -
Transmita as informações de credenciais usando variáveis de ambiente.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use. var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. // Load the default configurations of the OSS SDK. The configurations automatically read credential information, such as the AccessKey pair, from environment variables. var cfg = OSS.Configuration.LoadDefault(); // Explicitly specify that environment variables are used to obtain credentials for identity verification. The format is OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN. cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider(); // Set the region of the bucket. cfg.Region = region; // If an endpoint is specified, the default endpoint is overwritten. if(endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance based on the configurations. using var client = new OSS.Client(cfg);
Credenciais estáticas
Codifique as credenciais de acesso definindo diretamente o par AccessKey temporário.
Não incorpore credenciais de acesso em aplicações em ambiente de produção. Este método destina-se apenas a testes.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var cfg = OSS.Configuration.LoadDefault();
// Specify the temporary AccessKey ID and AccessKey secret, not the AccessKey ID and AccessKey secret of an Alibaba Cloud account.
// Note that the AccessKey ID obtained from STS starts with STS, as shown in the following code.
var access_key_id = "STS.****************";
var access_key_secret = "yourAccessKeySecret";
// Specify the obtained STS token.
var securityToken = "yourSecurityToken";
// Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey secret, and STS token.
cfg.CredentialsProvider = new OSS.Credentials.StaticCredentialsProvider(access_key_id, access_key_secret, securityToken);
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
Usar um ARN de função RAM
Use um ARN de função RAM para inicializar o provedor de credenciais para acesso ao OSS entre contas. A ferramenta Credentials obtém e atualiza automaticamente os tokens STS por meio da operação AssumeRole. Utilize o parâmetro policy para restringir permissões.
Uma conta Alibaba Cloud possui permissões totais sobre todos os recursos. Credenciais vazadas expõem seu sistema a riscos significativos de segurança. Utilize o par AccessKey de um usuário RAM com as permissões mínimas necessárias.
O AccessKey ID e o AccessKey secret são exibidos apenas no momento da criação. Salve-os imediatamente — credenciais perdidas não podem ser recuperadas. Criar um par AccessKey.
Obtenha um ARN de função RAM: Criar uma função RAM.
-
Adicione a dependência Aliyun.Credentials.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json -
Configure as credenciais de acesso usando um par AccessKey e um ARN de função RAM.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use. var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. // Alibaba Cloud credential configuration - Use a RAM role ARN. // For more information about credential types, see https://github.com/aliyun/credentials-csharp. var credConfig = new Aliyun.Credentials.Models.Config() { // Specify the credential type as a RAM role ARN. Type = "ram_role_arn", // Read the AccessKey ID from an environment variable. AccessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"), // Read the AccessKey secret from an environment variable. AccessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"), // The ARN of the RAM role. Format: acs:ram::USER_Id:role/ROLE_NAME. // You can also set this parameter using the ALIBABA_CLOUD_ROLE_ARN environment variable. RoleArn = "acs:ram::***************:role/******", // The name of the role session. This parameter is used to identify the current session. RoleSessionName = "<RoleSessionName>", // Optional. The permission policy to be assumed. Policy = "<Policy>", // Optional. The validity period of the STS token in seconds. RoleSessionExpiration = 3600, }; // Create a credential client instance to obtain a temporary access credential. var credClient = new Aliyun.Credentials.Client(credConfig); // Convert the common credential to a credential provider required by the OSS SDK. var credentialsProvider = new OSS.Credentials.CredentialsProviderFunc(() => { // Obtain the temporary credential. var credential = credClient.GetCredential(); // Construct a credential object required by the OSS SDK. return new OSS.Credentials.Credentials( credential.AccessKeyId, // The temporary AccessKey ID. credential.AccessKeySecret, // The temporary AccessKey secret. credential.SecurityToken); // The STS token. }); // Load the default configurations of the OSS SDK. // By default, credential information is loaded from environment variables. In this example, it is overwritten by the custom credential. var cfg = OSS.Configuration.LoadDefault(); // Set the OSS region. cfg.Region = region; // Set the custom credential provider. cfg.CredentialsProvider = credentialsProvider; // If a custom endpoint is specified, the default setting is overwritten. if (endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance based on the configurations. using var client = new OSS.Client(cfg); // Create a paginator for the ListBuckets operation. // This is used to obtain all OSS buckets under the current account. var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest()); // Asynchronously iterate through the paginated results of the buckets. Console.WriteLine("Buckets:"); await foreach (var page in paginator.IterPageAsync()) { // Traverse the buckets on each page. foreach (var bucket in page.Buckets ?? []) { // Output bucket information: name, storage class, and location. Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}"); } }
Usar uma função RAM do ECS
Para aplicações em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes, use uma função RAM do ECS para inicializar o provedor de credenciais. Isso associa uma função à instância ou ao nó do Container Service for Kubernetes para atualizar automaticamente os tokens STS sem gerenciamento manual de credenciais. Criar uma função RAM.
-
Adicione a dependência Aliyun.Credentials.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json -
Configure a credencial de acesso usando uma função RAM do ECS.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use. using Aliyun.Credentials.Models; var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. // Create a credential configuration and use an ECS RAM role for authentication. var credConfig = new Aliyun.Credentials.Models.Config() { // The credential type. Type = "ecs_ram_role", // The role name. This parameter is optional. If you do not specify this parameter, the role name is automatically obtained. We recommend that you set this parameter to reduce requests. RoleName = "<RoleName>" }; // Create a credential client to obtain a temporary access credential. var credClient = new Aliyun.Credentials.Client(credConfig); // Convert the common credential to a credential provider required by the OSS SDK. var credentialsProvider = new OSS.Credentials.CredentialsProviderFunc(() => { // Obtain the temporary credential. var credential = credClient.GetCredential(); // Construct a credential object required by the OSS SDK. return new OSS.Credentials.Credentials( credential.AccessKeyId, // The temporary AccessKey ID. credential.AccessKeySecret, // The temporary AccessKey secret. credential.SecurityToken); // The STS token. }); // Load the default configurations of the OSS client. var cfg = OSS.Configuration.LoadDefault(); // Set the OSS region. cfg.Region = region; // Set the custom credential provider. cfg.CredentialsProvider = credentialsProvider; // If a custom endpoint is specified, the default setting is overwritten. if (endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance based on the configurations. using var client = new OSS.Client(cfg); // Obtain all OSS buckets under the current role account. var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest()); // Asynchronously iterate through the paginated results of the buckets. Console.WriteLine("Buckets:"); await foreach (var page in paginator.IterPageAsync()) { // Traverse the buckets on each page. foreach (var bucket in page.Buckets ?? []) { // Output bucket information: name, storage class, and location. Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}"); } }
Usar um ARN de função OIDC
Para aplicações não confiáveis em nós de trabalho do Container Service for Kubernetes, use RRSA (RAM Roles for Service Accounts) com um ARN de função OIDC para isolar permissões no nível do pod. O cluster monta arquivos de token OIDC em cada pod e injeta configurações nas variáveis de ambiente. A ferramenta Credentials chama AssumeRoleWithOIDC para obter tokens STS automaticamente, eliminando o gerenciamento manual de credenciais. Isolar permissões de Pod com base em RRSA.
-
Adicione a dependência Aliyun.Credentials.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json
-
Configure a credencial de acesso usando um ARN de função OIDC.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use. using Aliyun.Credentials.Models; var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. // Create a credential configuration and use an OIDC role ARN for authentication. var credConfig = new Aliyun.Credentials.Models.Config() { // The credential type. Type = "oidc_role_arn", // Format: acs:ram::USER_Id:role/ROLE_NAME. // roleArn is optional. You can set the ALIBABA_CLOUD_ROLE_ARN environment variable instead. RoleArn = "<RoleArn>", // Format: acs:ram::USER_Id:oidc-provider/OIDC_IdP_name. // OIDCProviderArn is optional. You can set the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable instead. OIDCProviderArn = "<OIDCProviderArn>", // Format: path. // OIDCTokenFilePath is optional. You can set the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable instead. OIDCTokenFilePath = "/Users/xxx/xxx", // The name of the role session. RoleSessionName = "<RoleSessionName>", // Optional. The permission policy to be assumed. Policy = "<Policy>", // Optional. The validity period of the STS token. RoleSessionExpiration = 3600, }; // Create a credential client to obtain a temporary access credential. var credClient = new Aliyun.Credentials.Client(credConfig); // Convert the common credential to a credential provider required by the OSS SDK. var credentialsProvider = new OSS.Credentials.CredentialsProviderFunc(() => { // Obtain the temporary credential. var credential = credClient.GetCredential(); // Construct a credential object required by the OSS SDK. return new OSS.Credentials.Credentials( credential.AccessKeyId, // The temporary AccessKey ID. credential.AccessKeySecret, // The temporary AccessKey secret. credential.SecurityToken); // The STS token. }); // Load the default configurations of the OSS client. var cfg = OSS.Configuration.LoadDefault(); // Set the OSS region. cfg.Region = region; // Set the custom credential provider. cfg.CredentialsProvider = credentialsProvider; // If a custom endpoint is specified, the default setting is overwritten. if (endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance based on the configurations. using var client = new OSS.Client(cfg); // Obtain all OSS buckets under the current role account. var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest()); // Asynchronously iterate through the paginated results of the buckets. Console.WriteLine("Buckets:"); await foreach (var page in paginator.IterPageAsync()) { // Traverse the buckets on each page. foreach (var bucket in page.Buckets ?? []) { // Output bucket information: name, storage class, and location. Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}"); } }
Usar credenciais de acesso personalizadas
Implemente um provedor de credenciais personalizado caso os métodos anteriores não atendam aos seus requisitos.
Use a classe Credentials.CredentialsProviderFunc
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
// Explicitly set the access credentials. This is for demonstration purposes only. In actual projects, you can obtain the credentials from environment variables.
var AccessKeyId = "your AccessKeyId"; // Required. The AccessKey ID of the RAM user or the temporary AccessKey ID obtained from STS.
var AccessKeySecret = "your AccessKeySecret"; // Required. The AccessKey secret of the RAM user or the temporary AccessKey secret obtained from STS.
// var SecurityToken = "your STS Token"; // Optional. You can configure this variable if you use a temporary access credential.
// Convert the common credential to a credential provider required by the OSS SDK.
var credentialsProvider = new OSS.Credentials.CredentialsProviderFunc(() =>
{
// Use a long-term credential to construct a credential object required by the OSS SDK.
return new OSS.Credentials.Credentials(
AccessKeyId, // The AccessKey ID of the RAM user.
AccessKeySecret); // The AccessKey secret of the RAM user.
// Use a temporary access credential to construct a credential object required by the OSS SDK.
// return new OSS.Credentials.Credentials(
// AccessKeyId, // The temporary AccessKey ID.
// AccessKeySecret, // The temporary AccessKey secret.
// SecurityToken); // The STS token.
});
// Load the default configurations of the OSS client.
var cfg = OSS.Configuration.LoadDefault();
// Set the OSS region.
cfg.Region = region;
// Set the custom credential provider.
cfg.CredentialsProvider = credentialsProvider;
// If a custom endpoint is specified, the default setting is overwritten.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);
// Obtain all OSS buckets under the current role account.
var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());
// Asynchronously iterate through the paginated results of the buckets.
Console.WriteLine("Buckets:");
await foreach (var page in paginator.IterPageAsync())
{
// Traverse the buckets on each page.
foreach (var bucket in page.Buckets ?? [])
{
// Output bucket information: name, storage class, and location.
Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
}
}
Código de exemplo
O OSS SDK para C# V2 fornece códigos de exemplo para operações comuns.
|
Exemplo |
Arquivo de exemplo no GitHub |
|
Obter a capacidade de armazenamento de um bucket (C# SDK V2) |
|
|
Fazer upload de um objeto usando uma URL assinada (C# SDK V2) |
|