Quick integration
Integrate OSS SDK for C# V2:
Prerequisites
-
Requires
.NET Framework 4.7.1or later. -
Supports
.NET Standard 2.0and later. -
Supports
.NET 5.0and later. -
To install or update your .NET environment:
-
For .NET Framework: Go to the official Microsoft website to download and install .NET Framework 4.7.1 or later.
-
For .NET Standard: Ensure a compatible .NET implementation is installed (.NET Framework, .NET, or other supporting platforms).
-
For .NET: Go to the official .NET website to download and install .NET 5.0 or later.
-
Install the SDK
Use the latest OSS SDK for C# V2 to ensure the sample code runs as expected.
Install using NuGet
-
Check if NuGet is installed:
-
Ensure NuGet is installed in Visual Studio. If not, open Visual Studio Installer via Tools > Get Tools and Features, then select the .NET desktop development or ASP.NET and web development workload.
-
-
Open the project:
-
Create a project or open an existing project in Visual Studio.
-
-
Open the NuGet Package Manager:
-
In the menu bar, choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
-
-
Search for and install the SDK:
-
On the Browse tab of the NuGet Package Manager, search for
AlibabaCloud.OSS.V2. -
Select
AlibabaCloud.OSS.V2from the results. Ensure you select the latest stable version. -
Click Install and wait for the installation to complete.
-
-
Verify the installation:
-
After installation,
AlibabaCloud.OSS.V2appears under References in Solution Explorer.
-
Install by importing the project
-
Clone the GitHub repository:
-
Open a command prompt or Git Bash and run the following command to clone the repository:
git clone https://github.com/aliyun/alibabacloud-oss-csharp-sdk-v2.git
-
-
Add the project to your solution:
-
In Visual Studio, right-click your solution and choose Add > Existing Project....
-
Browse to the cloned source code directory, select the
AlibabaCloud.OSS.V2.csprojfile, and then click Open.
-
-
Add a project reference:
-
Right-click your project and choose Add > Reference....
-
In the dialog box that appears, go to the Projects tab, find and select the
AlibabaCloud.OSS.V2project, and then click OK.
-
Configure access credentials
Configure access credentials using the AccessKey pair of a RAM user.
-
In the RAM console, create a RAM user with a Permanent AccessKey Pair. Save the AccessKey pair and grant
AliyunOSSFullAccesspermission to the RAM user. -
Configure environment variables using the AccessKey pair of the RAM user.
Linux
-
Run the following commands in the command-line interface to append the environment variable settings to the
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Run the following command to apply the configuration.
source ~/.bashrc -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to check the default shell type.
echo $SHELL-
Follow the steps for your default shell type.
Zsh
-
Run the following commands to append the environment variable settings to the
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Run the following command to apply the configuration.
source ~/.zshrc -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Run the following command to apply the configuration.
source ~/.bash_profile -
Run the following commands to verify that the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in Command Prompt.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Run the following commands to verify that the environment variables are configured.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Run the following commands in 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)-
Run the following commands to verify that the environment variables are configured.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Initialize the client
Initialize an OSSClient with the region and endpoint, then run the test code.
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.
A successful upload returns the following output:
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==
Client configurations
Use a custom domain name
Objects accessed through the default OSS endpoint may not preview in browsers. Map a custom domain name to access OSS to enable browser previews and CDN acceleration.
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...
Use an internal endpoint
Use an internal endpoint to access OSS in the same region, reducing traffic costs and increasing access speed.
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...
Use a transfer acceleration endpoint
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...
Use a private domain name
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...
Use an Alibaba Gov Cloud endpoint
Configure an OSSClient with a Gov Cloud endpoint:
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...
Access credential configurations
OSS supports multiple credential initialization methods. Choose one based on your authentication requirements.
Use the AccessKey pair of a RAM user
Initialize the credential provider with an AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user. Best suited for secure environments that require long-term OSS access without frequent credential rotation. Manual AccessKey pair maintenance is required.
-
An Alibaba Cloud account has full permissions on all resources. Leaked credentials expose your system to significant security risks. Use the AccessKey pair of a RAM user with minimum required permissions instead.
-
The AccessKey ID and AccessKey secret are shown only at creation time. Save them immediately — lost credentials cannot be recovered. Create an AccessKey pair.
Environment variables
-
Configure environment variables using the AccessKey pair of a RAM user.
Linux
-
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Apply the changes.
source ~/.bashrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to view the default shell type:
echo $SHELL-
Configure environment variables based on the default shell type.
Zsh
-
Run the following commands to add the configurations of the environment variables to the
~/.zshrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to add the configurations of the environment variables to the
~/.bash_profilefile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Run the following commands in 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)-
Check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
-
After modifying the system environment variables, restart your IDE, CLI, and other runtime environments to load the updated values.
-
Pass the credential information using environment variables.
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);
Static credentials
Hard-code access credentials by setting the AccessKey pair directly.
Do not embed access credentials in applications in a production environment. This method is for testing purposes only.
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);
Use an STS token
Use temporary identity credentials (AccessKey ID, AccessKey secret, and security token) from STS to initialize the credential provider for temporary OSS access. This method requires manual STS token maintenance and refresh.
-
Quickly obtain an STS token by calling AssumeRole.
-
Obtain an STS token using an SDK: Use an STS token to access OSS.
-
You must specify an expiration time when you generate an STS token. The STS token becomes invalid and cannot be used after it expires.
-
STS Endpoints.
Environment variables
-
Set environment variables using temporary identity credentials.
Mac OS X/Linux/Unix
Warning-
Use the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey pair of a RAM user.
-
The AccessKey ID obtained from STS starts with `STS.`, for example, `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
Warning-
Use the temporary identity credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS, not the AccessKey pair of a RAM user.
-
The AccessKey ID obtained from STS starts with `STS.`, for example, `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> -
-
Pass the credential information using environment variables.
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);
Static credentials
Hard-code access credentials by setting the temporary AccessKey pair directly.
Do not embed access credentials in applications in a production environment. This method is for testing purposes only.
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.StaticCredentialsProvide(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);
Use a RAM role ARN
Use a RAM role ARN to initialize the credential provider for cross-account OSS access. The Credentials tool automatically obtains and refreshes STS tokens via the AssumeRole operation. Use the policy parameter to restrict permissions.
-
An Alibaba Cloud account has full permissions on all resources. Leaked credentials expose your system to significant security risks. Use the AccessKey pair of a RAM user with minimum required permissions instead.
-
The AccessKey ID and AccessKey secret are shown only at creation time. Save them immediately — lost credentials cannot be recovered. Create an AccessKey pair.
-
Obtain a RAM role ARN: Create a RAM role.
-
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json -
Configure the access credentials using an AccessKey pair and a RAM role ARN.
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.CredentialsProvideFunc(() => { // 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}"); } }
Use an ECS RAM role
For applications on ECS instances, ECI instances, or Container Service for Kubernetes worker nodes, use an ECS RAM role to initialize the credential provider. This associates a role with the instance or Container Service for Kubernetes node to auto-refresh STS tokens without manual credential management. Create a RAM role.
-
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json -
Configure the access credential using an ECS RAM role.
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}"); } }
Use an OIDC role ARN
For untrusted applications on Container Service for Kubernetes worker nodes, use RRSA (RAM Roles for Service Accounts) with an OIDC role ARN to isolate pod-level permissions. The cluster mounts OIDC token files to each pod and injects configuration into environment variables. The Credentials tool calls AssumeRoleWithOIDC to obtain STS tokens automatically, eliminating manual credential management. Isolate Pod permissions based on RRSA.
-
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json
-
Configure the access credential using an OIDC role ARN.
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.CredentialsProvideFunc(() => { // 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}"); } }
Use custom access credentials
Implement a custom credential provider if the preceding methods do not meet your requirements.
Use the Credentials.CredentialsProvideFunc interface
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.CredentialsProvideFunc(() =>
{
// 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}");
}
}
Sample code
OSS SDK for C# V2 provides sample code for common operations.
|
Sample |
GitHub sample file |