Quick start
Follow these steps to get started with the OSS SDK for C# 2.0:
Environment preparation
Requires
.NET Framework 4.7.1or a later version.Requires
.NET Standard 2.0or a later version.Requires
.NET 5.0or a later version.If your computing environment does not meet these requirements, follow these steps:
For .NET Framework: Download and install .NET Framework 4.7.1 or a later version from the Microsoft official website.
For .NET Standard: As a specification, .NET Standard is supported by .NET implementations such as .NET Framework or .NET. Ensure you have a compatible .NET implementation installed.
For .NET: Download and install .NET 5.0 or a later version from the .NET official website.
Install the SDK
We recommend using the latest version of the OSS SDK for C# V2 to ensure that the sample code in this topic runs as expected.
Install using NuGet
Check if NuGet is installed:
Ensure that the NuGet Package Manager is installed in Visual Studio. If it is not installed, open Visual Studio Installer by choosing Tools -> Get Tools and Features. On the Workloads tab, select .NET desktop development or ASP.NET and web development. These workloads automatically include the NuGet Package Manager.
Open the project:
Create a new 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.In the search results, find and select
AlibabaCloud.OSS.V2. View its details and select the latest stable version.Click Install. Wait for the installation to complete.
Verify the installation:
After installation,
AlibabaCloud.OSS.V2appears under References in Solution Explorer. You can now use the SDK features in your project.
Import 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 click Open.
Add a project reference:
Right-click your project and choose Add -> Reference....
In the dialog box, go to the Projects tab, select the
AlibabaCloud.OSS.V2project, and click OK.
Configure access credentials
Configure access credentials with a RAM user's AccessKey pair.
From the RAM console, create a RAM user with a permanent AccessKey pair, save the AccessKey pair, and then grant the user the
AliyunOSSFullAccesspermission.Set the environment variables using the RAM user's AccessKey pair.
Linux
Run the following commands to append 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'" >> ~/.bashrcRun the following command to apply the changes.
source ~/.bashrcRun the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command to check your default shell type.
echo $SHELLFollow the steps for your default shell type.
Zsh
Run the following commands to append 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'" >> ~/.zshrcRun the following command to apply the changes.
source ~/.zshrcRun the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to append 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_profileRun the following command to apply the changes.
source ~/.bash_profileRun the following commands to verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Run the following commands in CMD to set the environment variables.
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 set.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Run the following commands in PowerShell to set the environment variables.
[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 set.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Initialize the client
To run this sample, initialize an OSSClient with the region and endpoint.
using System.Text; // Import the System.Text namespace to handle character encoding, such as UTF-8.
using OSS = AlibabaCloud.OSS.V2; // Alias the Alibaba Cloud OSS SDK to simplify subsequent code.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, for China (Hangzhou), set this parameter to "cn-hangzhou".
var bucket = "your-bucket-name"; // Required. The name of the destination bucket.
var endpoint = null as string; // Optional. The endpoint for accessing OSS. If null, the SDK generates an endpoint based on the region. For example, the endpoint for China (Hangzhou) is "https://oss-cn-hangzhou.aliyuncs.com".
var key = "your-object-key"; // Required. The key of the object to upload. Example format: folder/objectName.
// Load the default SDK configuration. This automatically reads credentials (such as an AccessKey pair) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the provider to use environment variables for authentication (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region in the configuration.
cfg.Region = region;
// If a custom endpoint is specified, it overrides the default.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration.
using var client = new OSS.Client(cfg);
// Define the content to upload. This example uses a string, but you can also use a file stream or a byte array.
var content = "hello oss!";
// Convert the string to a UTF-8 encoded byte array and wrap it in a MemoryStream.
// MemoryStream is suitable for small uploads. For larger files, consider using a FileStream.
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
// Asynchronously upload the object.
var result = await client.PutObjectAsync(new OSS.Models.PutObjectRequest()
{
Bucket = bucket, // The name of the destination bucket.
Key = key, // The unique key for the object within the bucket.
Body = bodyStream // The content stream to upload.
});
// Print the upload result.
Console.WriteLine("PutObject done");
Console.WriteLine($"StatusCode: {result.StatusCode}"); // The HTTP status code.
Console.WriteLine($"RequestId: {result.RequestId}"); // The request ID, used for troubleshooting with Alibaba Cloud.
Console.WriteLine("Response Headers:"); // Response headers.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Print all response headers.A successful upload produces 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 configuration
Using a custom domain name
When you access OSS by using the default domain name, you may encounter issues such as file access being denied or files that cannot be previewed. By accessing OSS by using a custom domain name, you can not only preview files directly in a browser but also use CDN acceleration for distribution.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the OSS SDK to simplify the code.
var region = "cn-hangzhou"; // Required. Specify the bucket's region. For example, use "cn-hangzhou" for China (Hangzhou).
var endpoint = "https://www.example-***.com"; // Required. Specify your custom domain name, such as "www.example-***.com".
// Load the default configuration of the OSS SDK. It automatically reads credentials (such as an AccessKey pair) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Configure the client to get credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Specify the bucket's region.
cfg.Region = region;
// If an endpoint is specified, it overrides the default endpoint.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Note: This must be true to use a custom domain name via CNAME.
cfg.UseCName = true;
// Create the OSS client instance.
using var client = new OSS.Client(cfg);
// Use the client to perform operations...Use an internal endpoint
Using an internal endpoint to access OSS resources in the same region reduces data transfer costs and improves access speed.
using OSS = AlibabaCloud.OSS.V2; // Alias the Alibaba Cloud OSS SDK for convenience.
var region = "cn-hangzhou"; // Required: The region where the bucket is located, e.g., 'cn-hangzhou' for China (Hangzhou).
var endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com"; // Optional: The internal endpoint for OSS access. For example, the endpoint for China (Hangzhou) is https://oss-cn-hangzhou-internal.aliyuncs.com.
// Load the default OSS SDK configuration, which automatically reads credentials (e.g., the AccessKey pair) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Set the credentials provider to use environment variables for authentication (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket's region.
cfg.Region = region;
// If an endpoint is specified, it overrides the default one.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Alternatively, set cfg.UseInternalEndpoint = true to automatically use the internal endpoint.
// cfg.UseInternalEndpoint = true;
// Create an OSS client from the configuration.
using var client = new OSS.Client(cfg);
// Use the created client for subsequent operations...Use an acceleration endpoint
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK for brevity.
var region = "cn-hangzhou"; // Required. Your bucket's region. For example, in China (Hangzhou), set this to "cn-hangzhou".
var endpoint = "https://oss-accelerate.aliyuncs.com"; // Optional. The acceleration endpoint for the bucket's region.
// Load the default SDK configuration, which automatically reads credentials like your AccessKey pair from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly configure the credentials provider to use environment variables for authentication.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region for the client.
cfg.Region = region;
// If a custom endpoint is specified, it overrides the default.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Alternatively, set cfg.UseAccelerateEndpoint = true to automatically use the acceleration endpoint.
// cfg.UseAccelerateEndpoint = true;
// Create an OSS client instance with the configuration.
using var client = new OSS.Client(cfg);
// Use the client for subsequent operations. Use a dedicated domain name
using OSS = AlibabaCloud.OSS.V2; // Creates an alias for the Alibaba Cloud OSS SDK for simpler usage.
var region = "cn-hangzhou"; // Required. Your bucket's region. For example, set this to "cn-hangzhou" for China (Hangzhou).
var endpoint = "https://service.corp.example.com"; // Required. Your dedicated domain name. For example: https://service.corp.example.com.
// Loads the default SDK configuration, which automatically reads credentials, such as the AccessKey pair, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly sets the credentials provider to use environment variables for authentication (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Sets the region in the configuration.
cfg.Region = region;
// If a custom endpoint is specified, it overrides the default one.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Creates an OSS client instance from the configuration.
using var client = new OSS.Client(cfg);
// Use the created client to perform subsequent operations... Use a Gov Cloud endpoint
This example shows how to configure an OSSClient with an Alibaba Gov Cloud endpoint.
using OSS = AlibabaCloud.OSS.V2; // Alias the Alibaba Cloud OSS SDK for simpler usage.
var region = "cn-north-2-gov-1"; // Required. The bucket's region. For China North 2 (Ali Gov 1), use "cn-north-2-gov-1".
// Required. The internal endpoint for the bucket's region. For China North 2 (Ali Gov 1), use "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 SDK configuration. This reads credentials, such as AccessKey, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Set the provider to use environment variables for authentication. The variables are `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET`.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region in the configuration.
cfg.Region = region;
// If specified, the endpoint overrides the default.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client from the configuration.
using var client = new OSS.Client(cfg);
// Use the client for subsequent operations... Access credential configuration
OSS offers several methods to initialize credentials. Choose a method based on your authentication and authorization requirements.
RAM user's AccessKey pair
Initialize the credential provider with an AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user for applications that are in a secure environment, require long-term OSS access, and do not support frequent credential rotation. However, this method requires you to manually maintain the AccessKey pair, increasing security risks and maintenance complexity.
An Alibaba Cloud account has full permissions on all resources. Leaking the AccessKey pair of your Alibaba Cloud account exposes your system to significant security risks. We recommend that you do not use the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user that has only the minimum required permissions.
To create an AccessKey pair for a RAM user, see Create an AccessKey pair. A RAM user's AccessKey ID and AccessKey secret are displayed only upon creation. You must save them immediately. If you forget the AccessKey pair, create a new one.
Environment variables
Configure environment variables by 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 or refresh your compilation and runtime environments, such as your IDE, command-line interface, other desktop applications, and backend services. This ensures these environments load the latest variables.
Use environment variables to pass credential information.
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, for the China (Hangzhou) region, set the region to "cn-hangzhou". var endpoint = null as string; // Optional. The OSS endpoint. For example, for the China (Hangzhou) region, the endpoint is "https://oss-cn-hangzhou.aliyuncs.com". // Load the default OSS SDK configuration. This configuration automatically reads credential information, such as the AccessKey pair, from environment variables. var cfg = OSS.Configuration.LoadDefault(); // Explicitly set the credential provider to use the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables for authentication. cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider(); // Set the region for the bucket in the configuration. cfg.Region = region; // If an endpoint is specified, it overrides the default endpoint. if(endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance by using the configuration. using var client = new OSS.Client(cfg);
Static credentials
The following sample code shows how to hard-code access credentials by specifying the AccessKey pair.
Do not embed access credentials in your production applications. 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, for the China (Hangzhou) region, set the region to "cn-hangzhou".
var endpoint = null as string; // Optional. The OSS endpoint. For example, for the China (Hangzhou) region, the endpoint is "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 for the bucket in the configuration.
cfg.Region = region;
// If an endpoint is specified, it overrides the default endpoint.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance by using the configuration.
using var client = new OSS.Client(cfg);Use temporary STS credentials
This method requires you to manually maintain the STS token, posing security risks and increasing maintenance complexity. You must also manually refresh the STS token for repeated temporary access.
To obtain temporary identity credentials by calling an OpenAPI operation, see AssumeRole - Obtain temporary identity credentials for a role session.
To obtain temporary identity credentials by using an SDK, see Use temporary identity credentials from Security Token Service (STS) to access OSS.
The token automatically becomes invalid upon expiration.
For a list of STS endpoints, see Endpoints.
Environment variables
Set environment variables by using temporary identity credentials.
macOS, Linux, and Unix
WarningUse the temporary identity credentials (Access Key ID, Access Key Secret, and security token) obtained from STS, not the Access Key ID and Access Key Secret of a RAM user.
Note that the Access Key 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
WarningUse the temporary identity credentials (Access Key ID, Access Key Secret, and security token) obtained from STS, not the Access Key ID and Access Key Secret of a RAM user.
Note that the Access Key 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>Provide credentials using environment variables.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK for simpler usage. var region = "cn-hangzhou"; // Required. The region where your bucket is located. For this example, "cn-hangzhou" indicates China (Hangzhou). var endpoint = null as string; // Optional. The endpoint for accessing OSS. The endpoint for China (Hangzhou) is "https://oss-cn-hangzhou.aliyuncs.com". // Load the default OSS SDK configuration, which automatically reads credentials from environment variables. var cfg = OSS.Configuration.LoadDefault(); // Explicitly set the provider to use environment variables for authentication (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_SESSION_TOKEN). cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider(); // Set the region for the configuration. cfg.Region = region; // If an endpoint is specified, it overrides the default one. if(endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client from the configuration. using var client = new OSS.Client(cfg);
Static credentials
The following code demonstrates how to hard-code access credentials by directly setting the temporary Access Key ID, Access Key Secret, and security token.
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 for simpler usage.
var region = "cn-hangzhou"; // Required. The region where your bucket is located. For this example, "cn-hangzhou" indicates China (Hangzhou).
var endpoint = null as string; // Optional. The endpoint for accessing OSS. The endpoint for China (Hangzhou) is "https://oss-cn-hangzhou.aliyuncs.com".
var cfg = OSS.Configuration.LoadDefault();
// Specify the temporary Access Key ID and Access Key Secret from STS. These differ from the credentials of your Alibaba Cloud account.
// The Access Key ID from STS starts with the prefix "STS." as shown in the example below.
var access_key_id = "STS.****************";
var access_key_secret = "yourAccessKeySecret";
// Provide the security token obtained from STS.
var securityToken = "yourSecurityToken";
// Create a static credential provider and explicitly set the temporary Access Key ID, Access Key Secret, and security token.
cfg.CredentialsProvider = new OSS.Credentials.StaticCredentialsProvider(access_key_id, access_key_secret, securityToken);
// Set the region for the configuration.
cfg.Region = region;
// If an endpoint is specified, it overrides the default one.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client from the configuration.
using var client = new OSS.Client(cfg);Use a RAM role ARN
If your application needs delegated access to OSS, such as in cross-account scenarios, you can initialize the credential provider with a RAM role ARN. This method uses an STS token internally. When you provide a RAM role ARN, the Credentials utility automatically calls the AssumeRole operation to retrieve an STS token and refresh it before expiration. You can also assign a value to the policy parameter to further restrict the permissions of the RAM role.
An Alibaba Cloud account has full permissions on all resources. If the AccessKey pair of your Alibaba Cloud account is leaked, your system is exposed to significant security risks. For enhanced security, use an AccessKey pair from a RAM user with the minimum required permissions.
To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret are displayed only upon creation. You must save the AccessKey pair. If you forget an AccessKey pair, create a new one.
To obtain a RAM role ARN, see Create a role.
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.jsonConfigure 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 for convenience. var region = "cn-hangzhou"; // Required. The bucket's region. For example, for China (Hangzhou), set the region to "cn-hangzhou". var endpoint = null as string; // Optional. The OSS access endpoint. For example, for China (Hangzhou), set the endpoint to "https://oss-cn-hangzhou.aliyuncs.com". // Alibaba Cloud credential configuration for assuming a RAM role with an ARN. // For more examples of credential types, see https://github.com/aliyun/credentials-csharp. var credConfig = new Aliyun.Credentials.Models.Config() { // Sets the credential type to "ram_role_arn". Type = "ram_role_arn", // Reads the AccessKey ID from an environment variable. AccessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"), // Reads 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 by using the ALIBABA_CLOUD_ROLE_ARN environment variable. RoleArn = "acs:ram::***************:role/******", // A name for the role session, used for identification. RoleSessionName = "<RoleSessionName>", // Optional. A policy to restrict the permissions of the STS token. Policy = "<Policy>", // Optional. The STS token's validity period in seconds. RoleSessionExpiration = 3600, }; // Create a credential client instance to obtain temporary credentials. var credClient = new Aliyun.Credentials.Client(credConfig); // Adapt the generic credential to the provider format required by the OSS SDK. var credentialsProvider = new OSS.Credentials.CredentialsProvideFunc(() => { // Retrieve the temporary credential. var credential = credClient.GetCredential(); // Construct the 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 configuration of the OSS SDK. // The custom provider overrides the default behavior, which is to load credentials from environment variables. 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, it overrides the default setting. if (endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance from the configuration. using var client = new OSS.Client(cfg); // Creates a paginator for the ListBuckets operation // to retrieve all OSS buckets in the current account. var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest()); // Asynchronously iterate through the paginated results for buckets. Console.WriteLine("Buckets:"); await foreach (var page in paginator.IterPageAsync()) { // Iterate through 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
If your application runs on an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes, we recommend that you use an ECS RAM role to initialize the credential provider. This approach uses an STS token. An ECS RAM role lets you associate a role with an ECS instance, ECI instance, or Container Service for Kubernetes worker node to automatically refresh the STS token within the instance. This method eliminates the security risks and maintenance overhead of manually managing an AccessKey pair or an STS token. For more information, see CreateRole.
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.jsonConfigure the access credential using an ECS RAM role.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the OSS SDK to simplify usage. using Aliyun.Credentials.Models; // Required. The region where the bucket is located. For example, for China (Hangzhou), set the region to "cn-hangzhou". var region = "cn-hangzhou"; // Optional. The endpoint to access OSS. For example, for China (Hangzhou), the endpoint is "https://oss-cn-hangzhou.aliyuncs.com". var endpoint = null as string; // Create a credential configuration to authenticate with an ECS RAM role. var credConfig = new Aliyun.Credentials.Models.Config() { // The credential type. Type = "ecs_ram_role", // The role name. Optional. The role is automatically retrieved if this parameter is omitted. Set this parameter to reduce the number of requests. RoleName = "<RoleName>" }; // Create a credential client to obtain temporary access credentials. var credClient = new Aliyun.Credentials.Client(credConfig); // Wrap the credential in a provider function for the OSS SDK. var credentialsProvider = new OSS.Credentials.CredentialsProviderFunc(() => { // Obtain the temporary credential. var credential = credClient.GetCredential(); // Construct the 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 OSS client configuration. 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, it overrides the default setting. if (endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance from the configuration. using var client = new OSS.Client(cfg); // Retrieve all OSS buckets under the current role account. var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest()); // Asynchronously iterate through the paginated bucket results. Console.WriteLine("Buckets:"); await foreach (var page in paginator.IterPageAsync()) { // Iterate through 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
After you configure a RAM role for a worker node in Container Service for Kubernetes, applications in the pods on that node can retrieve the associated role's STS token from the metadata service, similar to applications deployed on an ECS instance. However, if you deploy untrusted applications on the cluster, such as those from customers whose code you cannot inspect, you should prevent them from retrieving the STS token of the instance RAM role associated with the worker node through the metadata service. To protect your cloud resources while allowing these untrusted applications to securely obtain the required STS tokens, you can use RAM Roles for Service Accounts (RRSA) to implement the principle of least privilege at the application level. The cluster automatically creates a service account OIDC token file, mounts it into each pod, and injects configuration details as environment variables. The credential utility then calls the AssumeRoleWithOIDC operation of the Security Token Service (STS) to exchange the OIDC token for an STS token bound to the role. This method eliminates the risks and maintenance overhead of managing static AccessKey pairs or STS tokens. For more information, see Isolate pod permissions by using RRSA.
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.json
Configure an access credential using an OIDC role ARN.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify its use. using Aliyun.Credentials.Models; var region = "cn-hangzhou"; // Required. The bucket's region. For example, for China (Hangzhou), set the region to "cn-hangzhou". var endpoint = null as string; // Optional. The endpoint to access OSS. For example, for China (Hangzhou), set the endpoint to "https://oss-cn-hangzhou.aliyuncs.com". // Create a credential configuration for authentication by using an OIDC role ARN. 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_PROVIDER_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 role session name. RoleSessionName = "<RoleSessionName>", // Optional. Restricts the permissions of the STS token. Policy = "<Policy>", // Optional. The validity period of the STS token in seconds. RoleSessionExpiration = 3600, }; // Create a credential client to obtain a temporary access credential. var credClient = new Aliyun.Credentials.Client(credConfig); // Convert the common credential to the credential provider required by the OSS SDK. var credentialsProvider = new OSS.Credentials.CredentialsProvideFunc(() => { // Obtain the temporary credential. var credential = credClient.GetCredential(); // Construct the 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 security token (STS token). }); // Load the default configuration 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, it overrides the default setting. if (endpoint != null) { cfg.Endpoint = endpoint; } // Create an OSS client instance from the configuration. using var client = new OSS.Client(cfg); // Create a paginator to retrieve all OSS buckets under the current role account. var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest()); // Asynchronously iterate through the paginated bucket results. Console.WriteLine("Buckets:"); await foreach (var page in paginator.IterPageAsync()) { // Iterate through 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}"); } }
Custom access credential
If the above methods for configuring credentials are unsuitable, you can implement a custom provider.
Use the Credentials.CredentialsProvideFunc delegate.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK for convenience.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, for China (Hangzhou), set the region to "cn-hangzhou".
var endpoint = null as string; // Optional. The OSS access endpoint. For example, for China (Hangzhou), the endpoint is "https://oss-cn-hangzhou.aliyuncs.com".
// These credentials are set for demonstration only. In production, retrieve them from a secure source, such as environment variables.
var AccessKeyId = "your-access-key-id"; // Required. The AccessKey ID of a RAM user or a temporary access credential.
var AccessKeySecret = "your-access-key-secret"; // Required. The AccessKey secret of a RAM user or a temporary access credential.
// var SecurityToken = "your-security-token"; // Optional. Configure this variable if you use a temporary access credential.
// Convert the generic credential into the credential provider required by the OSS SDK.
var credentialsProvider = new OSS.Credentials.CredentialsProvideFunc(() =>
{
// Use a long-term credential to construct the 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 the credential object required by the OSS SDK.
// return new OSS.Credentials.Credentials(
// AccessKeyId, // The temporary AccessKey ID.
// AccessKeySecret, // The temporary AccessKey secret.
// SecurityToken); // The security token.
});
// Load the default configuration of the OSS client.
var cfg = OSS.Configuration.LoadDefault();
// Set the OSS region.
cfg.Region = region;
// Set the custom credential provider.
cfg.CredentialsProvider = credentialsProvider;
// A custom endpoint, if specified, overrides the default.
if (endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance from the configuration.
using var client = new OSS.Client(cfg);
// Retrieve all OSS buckets under the current role account.
var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());
// Asynchronously iterate through the paginated results for buckets.
Console.WriteLine("Buckets:");
await foreach (var page in paginator.IterPageAsync())
{
// Iterate through 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
The OSS SDK for C# V2 provides extensive sample code for reference or direct use in your applications.
Sample | GitHub sample file |