Para fazer requisições ao Object Storage Service (OSS) com o kit de desenvolvimento de software (SDK) C#, configure as credenciais de acesso. Os serviços da Alibaba Cloud usam essas credenciais para verificar sua identidade e permissões de acesso. Forneça as credenciais de diversas formas, conforme os requisitos de autenticação e autorização do seu cenário.
Observações
Para obter informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.
Para criar um par de AccessKey para um usuário do Resource Access Management (RAM), consulte Criar um par de AccessKey.
Escolha um provedor de credenciais
O OSS oferece suporte a várias formas de inicializar um provedor de credenciais. Escolha o método de inicialização adequado aos seus requisitos de autenticação e autorização.
|
Método de inicialização do provedor de credenciais |
Cenários |
Requer um par de AccessKey ou token do Security Token Service (STS) pré-existente |
Tipo de credencial subjacente |
Validade da credencial |
Método de rotação ou atualização da credencial |
|
Aplicações executadas em ambiente seguro e estável, não vulnerável a ataques externos. Indicadas quando é necessário acesso de longo prazo aos serviços da Alibaba Cloud sem rotação frequente de credenciais. |
Sim |
Par de AccessKey |
Longo prazo |
Rotação manual |
|
|
Aplicações executadas em ambientes não confiáveis. Este método permite controlar o período de validade e as permissões do acesso. |
Sim |
Token STS |
Temporária |
Atualização manual |
|
|
Projetado para aplicações que exigem acesso autorizado aos serviços da Alibaba Cloud, como no caso de acesso entre contas. |
Sim |
Token STS |
Temporária |
Atualização automática |
|
|
Recomendado para aplicações executadas em instâncias ECS da Alibaba Cloud, instâncias ECI ou nós de trabalho do Container Service for Kubernetes. |
Não |
Token STS |
Temporária |
Atualização automática |
|
|
Mais indicado para aplicações não confiáveis executadas em nós de trabalho do Container Service for Kubernetes. |
Não |
Token STS |
Temporária |
Atualização automática |
|
|
Use este método quando a aplicação precisar obter credenciais de acesso de um sistema externo. |
Não |
Token STS |
Temporária |
Atualização automática |
|
|
Caso nenhum dos métodos anteriores atenda às suas necessidades, personalize a forma de obtenção das credenciais. |
Personalizado |
Personalizado |
Personalizado |
Personalizado |
Exemplos comuns de configuração
Usar o AK de um usuário RAM
Se sua aplicação estiver implantada em um ambiente seguro e estável, exigir acesso de longo prazo ao OSS e não permitir rotação frequente de credenciais, inicialize o provedor de credenciais com o par de AccessKey (AccessKey ID e AccessKey secret) de uma conta Alibaba Cloud ou de um usuário RAM. No entanto, esse método exige a manutenção manual do par de AccessKey, o que aumenta os riscos de segurança e a complexidade de manutenção. Para obter um par de AccessKey, consulte CreateAccessKey - Criar um par de AccessKey para uma conta Alibaba Cloud ou usuário RAM.
Variáveis de ambiente
Uma conta Alibaba Cloud possui permissões totais sobre todos os recursos. O vazamento de um par de AccessKey representa riscos significativos à segurança do sistema. Não recomendamos o uso do par de AccessKey da conta Alibaba Cloud. Em vez disso, utilize o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.
-
Defina as variáveis de ambiente usando um par de AccessKey.
Mac OS X, Linux, or Unix
export ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>Windows
set ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> -
Transmita as informações da credencial por meio de variáveis de ambiente.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Common.Authentication; // Obtain access credentials from environment variables. Before you run this code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. var accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, "")); // Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; var conf = new ClientConfiguration(); var client = new OssClient(endpoint, credentialsProvider, conf); client.SetRegion(region);
Credenciais estáticas
O exemplo de código a seguir demonstra como codificar as credenciais de acesso diretamente e definir explicitamente o par de AccessKey a ser utilizado.
Não incorpore credenciais de acesso em aplicações no ambiente de produção. Este método destina-se apenas a testes.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
// Replace the sample values with your actual AccessKey ID and AccessKey secret.
var accessKeyId = "LTAI5tQQx1DWEYK7********" ;
var accessKeySecret = "s5LkMqKmmKbt3zjs7MNJTj********" ;
var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, ""));
// Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
Usar uma credencial de acesso temporário STS
Caso sua aplicação necessite de acesso temporário ao OSS, inicialize o provedor de credenciais com uma credencial de identidade temporária (AccessKey ID, AccessKey secret e token de segurança) obtida no Security Token Service (STS). Contudo, essa abordagem demanda manutenção manual do token STS, elevando os riscos de segurança e a complexidade operacional. Além disso, para acessar o OSS temporariamente várias vezes, atualize o token STS manualmente.
Para obter rapidamente uma credencial de acesso temporário STS chamando uma operação OpenAPI, consulte AssumeRole - Obter uma credencial de identidade temporária para assumir uma função.
Para obter uma credencial de acesso temporário STS usando um SDK, consulte Usar uma credencial de acesso temporário STS para acessar o OSS.
Especifique um tempo de expiração ao gerar um token STS. O token torna-se inválido automaticamente após o vencimento e não pode ser reutilizado.
Para consultar a lista de endpoints do STS, consulte Endpoints.
Variáveis de ambiente
-
Defina as variáveis de ambiente utilizando uma credencial de identidade temporária.
Mac OS X, Linux, or Unix
export ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> export ALIBABA_CLOUD_SECURITY_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN> -
Transmita as informações da credencial por meio de variáveis de ambiente.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Common.Authentication; // Obtain access credentials from environment variables. Before you run this code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN environment variables are set. var accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); var token = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN"); var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, token)); // Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; var conf = new ClientConfiguration(); var client = new OssClient(endpoint, credentialsProvider, conf); client.SetRegion(region);
Credenciais estáticas
Codifique as credenciais diretamente na aplicação para definir explicitamente o par de AccessKey temporário a ser usado.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
// Replace the sample values with your actual temporary AccessKey ID, AccessKey secret, and security token.
var accessKeyId = "STS.NTZdStF79CVRTQuWCfXTT****";
var accessKeySecret = "5rm8PfEiK8enp56zzAMX4RbZUraoKbWXvCf1xAuT****"
var token = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN");
var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, token));
// Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
Mais exemplos de configuração para cenários específicos
Usar RAMRoleARN
Quando a aplicação exige acesso autorizado ao OSS, como em casos de acesso entre contas, inicialize o provedor de credenciais usando um RAMRoleARN. Esse método utiliza um token STS como credencial subjacente. Ao especificar o Alibaba Cloud Resource Name (ARN) de uma função RAM, a ferramenta de credenciais recupera um token STS do serviço STS e o atualiza automaticamente antes da expiração. Também é possível atribuir um valor a policy para restringir a função RAM a um conjunto menor de permissões.
Uma conta Alibaba Cloud possui permissões totais sobre todos os recursos. O vazamento de um par de AccessKey representa riscos significativos à segurança do sistema. Não recomendamos o uso do par de AccessKey da conta Alibaba Cloud. Em vez disso, utilize o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.
Para mais detalhes sobre como criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey secret de um usuário RAM são exibidos apenas no momento da criação. Salve-os imediatamente. Caso esqueça o AccessKey secret, crie um novo par de AccessKey para rotação.
Para obter um RAMRoleARN, consulte CreateRole - Criar uma função.
Instale a biblioteca de credenciais da Alibaba Cloud. Para mais informações, consulte Gerencie credenciais de acesso.
-
Configure as credenciais de acesso.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Common.Authentication; class CredentialsProviderWrapper : ICredentialsProvider { private Aliyun.Credentials.Client client; public CredentialsProviderWrapper(Aliyun.Credentials.Client client) { this.client = client; } public ICredentials GetCredentials() { var accessKeyId = client.GetAccessKeyId(); var accessKeySecret = client.GetAccessKeySecret(); var token = client.GetSecurityToken(); return new DefaultCredentials(accessKeyId, accessKeySecret, token); } public void SetCredentials(ICredentials creds) { } }; var config = new Aliyun.Credentials.Models.Config() { Type = "ram_role_arn", AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // By default, the following operations use parameter values that are directly entered. You can also add environment variables and use Environment.GetEnvironmentVariable("<variable_name>") to get the corresponding parameters. // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole RoleArn = "<RoleArn>", // The default environment variable for RoleArn is ALIBABA_CLOUD_ROLE_ARN. // The role session name. RoleSessionName = "<RoleSessionName>", // The default environment variable for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. }; var credentialsClient = new Aliyun.Credentials.Client(config); var credentialsProvider = new CredentialsProviderWrapper(credentialsClient); // Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; var conf = new ClientConfiguration(); var client = new OssClient(endpoint, credentialsProvider, conf); client.SetRegion(region);
Usar uma função RAM do ECS
Se a aplicação for executada em uma instância do Elastic Compute Service (ECS), em uma instância do Elastic Container Instance (ECI) ou em um nó de trabalho do Container Service for Kubernetes, recomendamos usar um ECSRAMRole para inicializar o provedor de credenciais. Esse método utiliza um token STS como credencial subjacente. Um ECSRAMRole permite associar uma função a uma instância ECS, a uma instância ECI ou a um nó de trabalho do Container Service for Kubernetes. Isso possibilita a atualização automática do token STS dentro da instância. Como não é necessário fornecer um par de AccessKey ou um token STS, eliminam-se os riscos associados à manutenção manual desses itens. Para obter um ECSRAMRole, consulte CreateRole - Criar uma função.
Instale a biblioteca de credenciais da Alibaba Cloud. Para mais informações, consulte Gerencie credenciais de acesso.
Configure um ECSRAMRole como credencial de acesso.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CredentialsProviderWrapper : ICredentialsProvider
{
private Aliyun.Credentials.Client client;
public CredentialsProviderWrapper(Aliyun.Credentials.Client client)
{
this.client = client;
}
public ICredentials GetCredentials()
{
var accessKeyId = client.GetAccessKeyId();
var accessKeySecret = client.GetAccessKeySecret();
var token = client.GetSecurityToken();
return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{
}
};
var config = new Aliyun.Credentials.Models.Config()
{
Type = "ecs_ram_role",
// Optional. The name of the ECS RAM role. If you do not specify this parameter, the role name is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
RoleName = "<RoleName>"
};
var credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
Usar OIDCRoleARN
Após configurar uma função RAM para os nós de trabalho no Container Service for Kubernetes, as aplicações nos pods desses nós podem recuperar o token STS da função associada por meio do serviço global de metadados, de forma semelhante às aplicações implantadas no ECS. Entretanto, se você implantar aplicações não confiáveis no cluster de contêineres — como aplicações enviadas por clientes cujo código não está visível para você —, talvez não queira que elas recuperem o token STS da função RAM da instância associada aos nós de trabalho via serviço global de metadados. Para evitar riscos de segurança aos seus recursos na nuvem e, ao mesmo tempo, permitir que essas aplicações não confiáveis recuperem com segurança os tokens STS necessários e alcancem a minimização de permissões no nível da aplicação, utilize o recurso RAM Roles for Service Accounts (RRSA). Esse método usa um token STS como credencial subjacente. Um cluster de contêineres da Alibaba Cloud cria e monta o arquivo de token OpenID Connect (OIDC) da conta de serviço correspondente para diferentes pods de aplicação e injeta as informações de configuração relevantes nas variáveis de ambiente. A ferramenta de credenciais recupera as informações de configuração das variáveis de ambiente e chama a operação AssumeRoleWithOIDC do STS para trocar o token OIDC por um token STS da função vinculada. Como não é necessário fornecer um par de AccessKey ou um token STS, eliminam-se os riscos associados à manutenção manual desses itens. Para mais informações, consulte Isolar permissões de pods com base no RRSA.
As seguintes variáveis de ambiente são injetadas:
ALIBABA_CLOUD_ROLE_ARN: O ARN da função RAM.
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: O ARN do provedor OIDC.
ALIBABA_CLOUD_OIDC_TOKEN_FILE: O caminho para o arquivo de token OIDC.
Configure um OIDCRoleArn como credencial de acesso.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CredentialsProviderWrapper : ICredentialsProvider
{
private Aliyun.Credentials.Client client;
public CredentialsProviderWrapper(Aliyun.Credentials.Client client)
{
this.client = client;
}
public ICredentials GetCredentials()
{
var accessKeyId = client.GetAccessKeyId();
var accessKeySecret = client.GetAccessKeySecret();
var token = client.GetSecurityToken();
return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{}
};
var config = new Aliyun.Credentials.Models.Config()
{
Type = "oidc_role_arn",
// The ARN of the RAM role. You can set RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable.
RoleArn = "<RoleArn>",
// The ARN of the OIDC provider. You can set OidcProviderArn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
OIDCProviderArn = "<OidcProviderArn>",
// The path to the OIDC token file. You can set OidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
OIDCTokenFilePath = "<OidcTokenFilePath>",
// The role session name. You can set RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
RoleSessionName = "<RoleSessionName>",
// Optional. A more restrictive access policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
Policy = "<Policy>",
RoleSessionExpiration = 3600
};
var credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
Usar CredentialsURI
Se a aplicação precisar recuperar credenciais da Alibaba Cloud de um sistema externo para garantir gerenciamento flexível de credenciais e acesso sem chaves, inicialize o provedor de credenciais usando um CredentialsURI. Esse método utiliza um token STS como credencial subjacente. A ferramenta de credenciais recupera um token STS da URI fornecida para concluir a inicialização do cliente de credenciais. Como não é necessário fornecer um par de AccessKey ou um token STS, eliminam-se os riscos associados à manutenção manual desses itens. O serviço de back-end que fornece a resposta do CredentialsURI deve implementar uma lógica de atualização automática para o token STS, garantindo que a aplicação sempre recupere credenciais válidas.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CredentialsProviderWrapper : ICredentialsProvider
{
private Aliyun.Credentials.Client client;
public CredentialsProviderWrapper(Aliyun.Credentials.Client client)
{
this.client = client;
}
public ICredentials GetCredentials()
{
var accessKeyId = client.GetAccessKeyId();
var accessKeySecret = client.GetAccessKeySecret();
var token = client.GetSecurityToken();
return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{}
};
var config = new Aliyun.Credentials.Models.Config()
{
// The credential type.
Type = "credentials_uri",
// The URI from which to obtain credentials. The format is http://local_or_remote_uri/. You can set CredentialsURI using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
CredentialsURI = "<CredentialsURI>"
};
var credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
Usar uma credencial de acesso personalizada
Caso nenhum dos métodos de configuração anteriores atenda aos seus requisitos, implemente a interface Credential Providers para personalizar a forma como as credenciais são fornecidas.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CustomCredentialsProvider : ICredentialsProvider
{
public CustomCredentialsProvider()
{
}
public ICredentials GetCredentials()
{
// TODO
// Custom method to obtain access credentials.
string accessKeyId;
string accessKeySecret;
//string token;
// Return long-term credentials: access_key_id, access_key_secret.
return new DefaultCredentials(accessKeyId, accessKeySecret, "");
// Return temporary credentials: access_key_id, access_key_secret, token.
// For temporary credentials, you must refresh the credentials based on their expiration time.
// return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{
}
};
var credentialsProvider = new CustomCredentialsProvider();
// Specify the endpoint of 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);