Quick integration
The following procedure describes how to integrate OSS SDK for C# 2.0:
Environment preparations
The SDK supports
.NET Framework 4.7.1and later.The SDK supports
.NET Standard 2.0and later.The SDK supports
.NET 5.0and later.If you do not have the required .NET environment or your version is outdated, follow these steps:
For .NET Framework: Go to the official Microsoft website to download and install .NET Framework 4.7.1 or later.
For .NET Standard: .NET Standard is an implementation specification supported by various .NET platforms, such as .NET Framework and .NET. Ensure that you have a compatible .NET implementation installed.
For .NET: Go to the official .NET website to download and install .NET 5.0 or later.
Install the SDK
Use the latest version of 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. The NuGet package manager is automatically included with these workloads.
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.In the search results, find and select
AlibabaCloud.OSS.V2. Ensure that you select the latest stable version.Click Install to install the package. Wait for the installation to complete.
Verify the installation:
After the installation is complete,
AlibabaCloud.OSS.V2appears under References in Solution Explorer. You can now use the features provided by the SDK in your project.
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, 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 that uses a Permanent AccessKey Pair, save the AccessKey pair, and then grant the
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'" >> ~/.bashrcRun the following command to apply the configuration.
source ~/.bashrcRun 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 $SHELLFollow 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'" >> ~/.zshrcRun the following command to apply the configuration.
source ~/.zshrcRun 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_profileRun the following command to apply the configuration.
source ~/.bash_profileRun 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 based on the region and endpoint, and 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.After you run the code, the following result is returned. This indicates that the file was uploaded successfully:
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
If you use the default OSS endpoint to access an object, the object may be inaccessible or fail to preview in a browser. You can map a custom domain name to access OSS. This lets you preview objects in browsers and use CDN to accelerate content delivery.
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
You can use an internal endpoint to access OSS resources in the same region. This reduces traffic costs and increases 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 an OSS-accelerated 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
The following sample code shows how to configure an OSSClient using 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 provides multiple methods to initialize credentials. Select a method based on your authentication and authorization requirements.
Use the AccessKey pair of a RAM user
You can use the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user to initialize the credential provider. This method is suitable if your application is deployed in a secure and stable environment, requires long-term access to OSS resources, and does not require frequent credential rotation. However, this method requires you to manually maintain the AccessKey pair, which poses security risks and increases maintenance complexity.
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. Do not use the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user to which you have granted the minimum required permissions.
For more information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. You must save the AccessKey pair when you create it. If you forget the AccessKey pair, you must create a new one.
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'" >> ~/.bashrcApply the changes.
source ~/.bashrcCheck 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 $SHELLConfigure 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'" >> ~/.zshrcApply the changes.
source ~/.zshrcCheck 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_profileApply the changes.
source ~/.bash_profileCheck 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 you modify the system environment variables, restart or refresh your compilation and runtime environments. These environments include the IDE, command-line interface, other desktop applications, and backend services. This ensures that the latest system environment variables are loaded.
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
The following sample code shows how to hard-code access credentials by explicitly setting the AccessKey pair.
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
If your application requires temporary access to OSS, you can use temporary identity credentials (AccessKey ID, AccessKey secret, and a security token) obtained from Security Token Service (STS) to initialize the credential provider. However, this method requires you to manually maintain the STS token, which poses security risks and increases maintenance complexity. Additionally, to temporarily access OSS multiple times, you must manually refresh the STS token.
For information about how to quickly obtain an STS token by calling an OpenAPI operation, see AssumeRole.
For information about how to obtain an STS token using an SDK, see 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.
For a list of STS endpoints, see Endpoints.
Environment variables
Set environment variables using temporary identity credentials.
Mac OS X/Linux/Unix
WarningUse 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
WarningUse 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
The following sample code shows how to hard-code access credentials by explicitly setting the temporary AccessKey pair.
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.StaticCredentialsProvider(access_key_id, access_key_secret, securityToken);
// Set the region of the bucket.
cfg.Region = region;
// If an endpoint is specified, the default endpoint is overwritten.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configurations.
using var client = new OSS.Client(cfg);Use a RAM role ARN
If your application requires authorization to access OSS, such as accessing OSS across different Alibaba Cloud accounts, you can use a RAM role Alibaba Cloud Resource Name (ARN) to initialize the credential provider. The underlying implementation of this method uses an STS token. When you specify the ARN of a RAM role, the Credentials tool obtains an STS token from STS. The tool also calls the AssumeRole operation to request a new STS token before the current session expires. Additionally, you can assign a value to the policy parameter to restrict the RAM role to a smaller set of permissions.
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. Do not use the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user to which you have granted the minimum required permissions.
For more information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. You must save the AccessKey pair when you create it. If you forget the AccessKey pair, you must create a new one.
For more information about how to obtain a RAM role ARN, see CreateRole.
Add the Aliyun.Credentials dependency.
dotnet add package Aliyun.Credentials --source https://api.nuget.org/v3/index.jsonConfigure 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
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. The underlying implementation of this method uses an STS token. An ECS RAM role lets you associate a role with an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes 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 because you do not need to provide them. For more information about how to obtain an ECS RAM role, 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 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
After you configure a RAM role for a worker node in Container Service for Kubernetes, applications in pods on that node can obtain the STS token of the associated role through the global meta service, similar to applications deployed on ECS. However, if untrusted applications are deployed on the container cluster, you may not want them to obtain the STS token of the instance RAM role that is associated with the worker node through the global meta service. An example of an untrusted application is an application submitted by your customers whose code is not open to you. To avoid compromising the security of your cloud resources while allowing these untrusted applications to securely obtain the required STS tokens and minimize permissions at the application level, you can use the RAM Roles for Service Accounts (RRSA) feature. The underlying implementation of this method uses an STS token. An Alibaba Cloud container cluster creates and mounts the corresponding service account OpenID Connect (OIDC) token file for each application pod and injects the relevant configuration information into environment variables. The Credentials tool retrieves the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the STS token of the bound role. This method eliminates the security risks and maintenance overhead of manually managing an AccessKey pair or an STS token because you do not need to provide them. For more information, see 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
If none of the preceding credential configuration methods meet your requirements, you can implement a custom method to obtain credentials.
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 a variety of sample code for your reference.
Sample | GitHub sample file |