Integrate Alibaba Cloud SDK V2.0 for .NET
Integrate Alibaba Cloud SDK into your .NET project to simplify API calls and reduce maintenance costs. Integration involves three steps: install the SDK, configure an access credential, and call API operations.
Prerequisites
-
.NET Framework 4.5 or later, or .NET Standard 2.0 or later.
-
C# 5.0 or later.
Install the SDK
-
Log on to SDKCenter and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.
-
On the Short Message Service page, in SDK generation, select V2.0, select C# in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.
View the source code and installation guidelines on GitHub.
Configure an access credential
Calling OpenAPI operations requires access credentials such as AccessKey or Security Token Service (STS) token. Store credentials in environment variables to prevent leaks. For best practices, see Securely use access credentials. The examples below use the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
Configuration method in Linux and macOS
Configure environment variables using the export command
A temporary environment variable set using the export command is valid only for the current session. The variable is cleared when the session ends. For long-term retention (LTR), add the export command to the startup configuration file of your operating system.
Configure the AccessKey ID and press Enter.
# Replace yourAccessKeyID with your AccessKey ID. export ALIBABA_CLOUD_ACCESS_KEY_ID=yourAccessKeyIDConfigure the AccessKey secret and press Enter.
# Replace yourAccessKeySecret with your AccessKey secret. export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecretVerify the configuration.
Run the
echo $ALIBABA_CLOUD_ACCESS_KEY_IDcommand. If the command returns the correct AccessKey ID, the configuration is successful.
Configuration method in Windows
Use the graphical user interface (GUI)
Procedure
The following steps describe how to set environment variables using the GUI in Windows 10.
On your desktop, right-click This PC and choose Properties > Advanced system settings > Environment Variables > New under System variables or User variables. Then, complete the configuration.
Variable
Example value
AccessKey ID
Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID
Variable value: yourAccessKeyID
AccessKey Secret
Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET
Variable value: yourAccessKeySecret
Test the configuration
Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%andecho %ALIBABA_CLOUD_ACCESS_KEY_SECRET%commands. If the commands return the correct AccessKey, the configuration is successful.
Use the command prompt (CMD)
Procedure
Open the command prompt as an administrator and run the following commands to add new environment variables to the system.
setx ALIBABA_CLOUD_ACCESS_KEY_ID yourAccessKeyID /M setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /MThe
/Mparameter indicates a system environment variable. You can omit this parameter when you set a user environment variable.Test the configuration
Click Start (or use the Win+R keyboard shortcut), click Run, enter `cmd`, and then click OK (or press Enter) to open the command prompt. Run the
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%andecho %ALIBABA_CLOUD_ACCESS_KEY_SECRET%commands. If the commands return the correct AccessKey, the configuration is successful.
Using Windows PowerShell
In PowerShell, you can set new environment variables that are valid for all new sessions:
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::User)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::User)To set environment variables for all users, you must have administrative permissions:
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)You can set temporary environment variables that are valid only for the current session:
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "yourAccessKeyID"
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "yourAccessKeySecret"In PowerShell, run the Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_ID and Get-ChildItem env:ALIBABA_CLOUD_ACCESS_KEY_SECRET commands. If the commands return the correct AccessKey, the configuration is successful.
Use the SDK
This example calls the SendSms operation of Short Message Service (SMS) . For more information about SendSms, see SendSms.
1. Initialize a request client
All API requests are sent through a client object. Initialize the client before calling any API operation. Multiple initialization methods are available. This example uses an AccessKey pair. For more information, see Manage access credentials.
-
Client objects (such as Dysmsapi Client instances) are thread-safe. You do not need to create an instance for each thread.
-
Do not frequently create client objects with the new keyword — this wastes resources and degrades performance. Use the singleton pattern to ensure only one Client instance per access credential and
endpoint.
public static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient(){
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// Required, ensure that the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in the code runtime environment.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required, ensure that the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in the code runtime environment.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
config.Endpoint = "dysmsapi.aliyuncs.com";
return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
}
2. Create a request object
Each API operation has a request object named <API operation name>Request. For example, the SendSms request object is SendSmsRequest. For more information about the parameters of the SendMessageToGlobe operation, see SendSms.
If an API operation has no request parameters, skip the request object. For example, the DescribeCdnSubList operation requires no request parameters.
// Create request object and set parameters
AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
{
// Replace with the phone number that receives SMS
PhoneNumbers = "",
// Replace with the SMS signature name
SignName = "",
// Replace with the SMS template code
TemplateCode = "",
// Replace with the actual values corresponding to the SMS template variables. Multiple parameters are supported.
TemplateParam = ""
};
3. Initiate the request
Call the API operation using the <API operation name>WithOptions method. This method takes two parameters: the request object from the preceding step and a runtime parameter for timeout and proxy configurations. For more information, see Advanced configuration.
If an API operation has no request parameters, only the runtime parameter is required. For example, only the runtime parameter is needed when you call the DescribeCdnSubList operation.
The response object is named <API operation name>Response. For example, the response object for the SendSms API operation is SendSmsResponse.
// Create runtime configuration
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.SDK.Dysmsapi20170525.Client client = CreateClient();
// Send request
AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsResponse sendSmsResponse = client.SendSmsWithOptions(sendSmsRequest, runtime);
4. Handle errors
The SDK classifies exceptions into two types:
-
TeaUnretryableException: Typically caused by network errors. Reported when the maximum retry count is reached.
-
TeaException: Typically caused by business errors.
For more information about how to handle SDK exceptions, see Exception handling.
Implement proper exception handling — including reporting, logging, and retries — to ensure system stability.
Click to view the complete sample code
File upload with the Advance operation
When you use Image Search or Visual Intelligence API (VIAPI) to process or upload on-premises images, the standard API does not support direct file uploads. Use the Advance operation to upload files through streams. The service temporarily stores uploaded files in OSS (default region: cn-shanghai) and reads them back when necessary. The following example calls the DetectBodyCount operation of VIAPI:
OSS temporary files are periodically cleared.
-
Initialize a request client
Specify both
RegionIdand the serviceendpoint.RegionIdsets the OSS region for temporary file storage. IfRegionIdis not set, the service may use a different region, causing API timeouts.public static AlibabaCloud.SDK.Facebody20191230.Client CreateClient() { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID. AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET. AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), }; config.RegionId = "cn-shanghai"; config.Endpoint = "facebody.cn-shanghai.aliyuncs.com"; return new AlibabaCloud.SDK.Facebody20191230.Client(config); } -
Create a request object
Create the
<API operation>AdvanceRequestrequest object and setImageURLObjectto pass the file stream.AlibabaCloud.SDK.Facebody20191230.Models.DetectBodyCountAdvanceRequest detectBodyCountAdvanceRequest = new AlibabaCloud.SDK.Facebody20191230.Models.DetectBodyCountAdvanceRequest { ImageURLObject = File.OpenRead(@"<FILE_PATH>"), // Replace <FILE_PATH> with the actual file path. }; -
Initiate a request
Call the
<API operation name>Advancemethod to send the request.// Configure the runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); AlibabaCloud.SDK.Facebody20191230.Client client = CreateClient(); // Send the request. AlibabaCloud.SDK.Facebody20191230.Models.DetectBodyCountResponse response = client.DetectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime); Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(response));
FAQ
-
How do I handle the "You are not authorized to perform this operation" error thrown by an API operation?
Cause: The RAM user's AccessKey pair lacks the required permissions.
Solution: Grant the required permissions to the RAM user. For more information, see Manage RAM user permissions.
For example, if the "You are not authorized to perform this operation" error is thrown by the SendSms API operation, create the following custom policy to grant the required permissions to the RAM user:
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "dysms:SendSms", "Resource": "*" } ] } -
How do I handle the "System.UnretryableException: One or more errors occurred" error thrown by an API operation?
Cause: The specified endpoint is not supported by this API operation.
Solution: Specify a supported endpoint and try again. For more information, see Endpoint configuration.
-
How do I handle the "ErrorCode":"InvalidAccessKeyId.NotFound","ErrorMessage":"Specified access key is not found" error thrown by an API operation?
Cause: The AccessKey pair was not passed correctly.
Solution: Verify that the AccessKey pair is passed correctly during client initialization.
Environment.GetEnvironmentVariable("XXX")reads theXXXvalue from environment variables.
For more information about how to handle SDK errors, see FAQ.