All Products
Search
Document Center

Alibaba Cloud SDK:Integrate Alibaba Cloud SDK V2.0 for .NET

Last Updated:Dec 04, 2025

To facilitate API calls, we recommend that you integrate with Alibaba Cloud SDK in your project. SDKs simplify the development process, quickly integrate features, and greatly reduce the O&M cost. To integrate with Alibaba Cloud SDK, perform the following steps: install Alibaba Cloud SDK, configure an access credential, and use the SDK. This topic describes how to integrate with Alibaba Cloud SDK.

Prerequisites

  • .Net Framework 4.5 or later is installed, or .Net Standard 2.0 or later is installed.

  • C# 5.0 or later is installed.

Import the SDK

  1. Log on to SDK Center and select the service whose SDK you want to use. In this example, Short Message Service (SMS) is selected.

  2. On the Short Message Service page, select C# in the All languages section. On the Quick Start tab, obtain the installation method of Short Message Service (SMS) SDK.image

Note

You can also view the source code and related installation guidelines on GitHub. For more information, see GitHub - aliyun/alibabacloud-csharp-sdk.

Configure an access credential

To call API operations of an Alibaba Cloud service, you must configure an access credential, such as an AccessKey pair or a Security Token Service (STS) token. To prevent AccessKey pair leaks, you can record the AccessKey pair in environment variables. For more information about other security solutions, see Credential security solutions. In this example, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are used to record AccessKey pairs.

Configure environment variables in Linux and macOS

Configure environment variables by using the export command

Important

The temporary environment variables configured by using the export command are valid only for the current session. After you exit the session, the configured environment variables become invalid. To configure permanent environment variables, you can add the export command to the startup configuration file of the corresponding operating system.

  • Configure the AccessKey ID and press Enter.

    # Replace <ACCESS_KEY_ID> with your AccessKey ID. 
    export ALIBABA_CLOUD_ACCESS_KEY_ID=yourAccessKeyID
  • Configure the AccessKey secret and press Enter.

    # Replace <ACCESS_KEY_SECRET> with your AccessKey secret. 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=yourAccessKeySecret
  • Check whether the configuration is successful.

    Run the echo $ALIBABA_CLOUD_ACCESS_KEY_ID command. If the valid AccessKey ID is returned, the environment variables are configured.

Configure environment variables in Windows

Use GUI

  • Procedure

    If you want to use GUI to configure environment variables in Windows 10, perform the following steps:

    On the Windows desktop, right-click This PC and select Properties. On the page that appears, click Advanced system settings. In the System Properties dialog box, click Environment Variables on the Advanced tab. In the Environment Variables dialog box, click New in the User variables or System variables section. Then, configure the variables described in the following table.

    Variable

    Example

    AccessKey ID

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_ID

    • Variable value: LTAI****************

    AccessKey Secret

    • Variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET

    • Variable value: yourAccessKeySecret

  • Check whether the configuration is successful.

    On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

Use CMD

  • Procedure

    Open a Command Prompt window as an administrator and run the following commands to add environment variables in the operating system:

    setx ALIBABA_CLOUD_ACCESS_KEY_ID yourAccessKeyID /M
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET yourAccessKeySecret /M

    /M indicates that the environment variable is of system level. You can choose not to use this parameter when you configure a user-level environment variable.

  • Check whether the configuration is successful.

    On the Windows desktop, click Start or press Win + R. In the Run dialog box, enter cmd. Then, click OK or press Enter. On the page that appears, run the echo %ALIBABA_CLOUD_ACCESS_KEY_ID% and echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET% commands. If the valid AccessKey pair is returned, the configuration is successful.

Use Windows PowerShell

In PowerShell, configure new environment variables. The environment variables apply to 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)

Configure environment variables for all users. You must run the following commands as an administrator.

[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_ID', 'yourAccessKeyID', [System.EnvironmentVariableTarget]::Machine)
[System.Environment]::SetEnvironmentVariable('ALIBABA_CLOUD_ACCESS_KEY_SECRET', 'yourAccessKeySecret', [System.EnvironmentVariableTarget]::Machine)

Configure temporary environment variables. The environment variables apply only to 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 valid AccessKey pair is returned, the configuration is successful.

Use the SDK

In this example, the SendMessageToGlobe API operation of Short Message Service (SMS) is called. For more information about SendMessageToGlobe, see SendMessageToGlobe.

1. Initialize a request client

In the SDK, all requests to API operations are sent from a client. Before you can an API operation, you must initialize the request client. You can use multiple methods to initialize a request client. In this example, an AccessKey pair is used to initialize a request client. For more information, see Manage access credentials.

Important
  • Client objects, such as Dysmsapi Client instances, are thread-safe, and can be used in multithreaded environments without security risks. You do not need to create an instance for each thread.

  • In development projects, we recommend that you do not use the new keyword to frequently create client objects. Otherwise, resource waste may increase and service perform may degrade. We recommend that you encapsulate the client in singleton mode. This ensures that only one Client instance is initialized for the same access credential and endpoint throughout the application lifecycle.

 public static AlibabaCloud.SDK.Dysmsapi20180501.Client CreateClient(){
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            config.Endpoint = "dysmsapi.aliyuncs.com";
            return new AlibabaCloud.SDK.Dysmsapi20180501.Client(config);
        }

2. Create a request object

When you call an API operation to pass parameters, you must use the request object provided by the SDK. Name the request object of the API operation in the following format: <API operation name>Request. For example, the request object of the SendMessageToGlobe API operation is SendMessageToGlobeRequest. For more information about the parameters, see the API reference. For more information about the parameters of the SendMessageToGlobe operation, see SendMessageToGlobe.

Note

If the API operation does not support request parameters, you do not need to create a request object. For example, the DescribeCdnSubList operation does not support request parameters.

// Create request object and set required input parameters
AlibabaCloud.SDK.Dysmsapi20180501.Models.SendMessageToGlobeRequest sendMessageToGlobeRequest = new AlibabaCloud.SDK.Dysmsapi20180501.Models.SendMessageToGlobeRequest
            {   
                // Please replace with the actual recipient number.
                To = "<PHONE_NUMBER>",
                // Please replace with the actual SMS content.
                Message = "<YOUR_MESSAGE>",
            };

3. The client initiates the request

When you use a request client to call an API operation, we recommend that you name the function in the following format: <API operation name>WithOptions. This function contains two parameters: the request object and the runtime parameter. The request object is created in the preceding step. The runtime parameter is used to specify the request action, such as timeout and proxy configurations. For more information, see Advanced configuration.

Note

If the API operation does not support request parameters, you do not need to specify a request object in the request. For example, you only need to specify the runtime parameter when you call the DescribeCdnSubList operation.

Name the response object of the API operation in the following format: <API operation name>Response. For example, the response object of the SendMessageToGlobe API operation is SendMessageToGlobeResponse.

 // Create runtime parameters.
 AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
 AlibabaCloud.SDK.Dysmsapi20180501.Client client = CreateClient();
 // Send a request.
 AlibabaCloud.SDK.Dysmsapi20180501.Models.SendMessageToGlobeResponse response = client.SendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);

4. Handle errors

Alibaba Cloud SDK V2.0 for .NET classifies exceptions into the following types:

  • TeaUnretryableException: In most cases, exceptions of this type are caused by network errors and are reported when the maximum number of retries are reached.

  • TeaException: In most cases, this type of exception is caused by business errors.

For more information about how to handle SDK exceptions, see Exception handling.

Important

We recommend that you take proper exception handling measures, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.

Click to view the complete sample code

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {
        public static AlibabaCloud.SDK.Dysmsapi20180501.Client CreateClient()
        {
    
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID is set.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Required, please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_SECRET is set.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
          
            config.Endpoint = "dysmsapi.aliyuncs.com";
            return new AlibabaCloud.SDK.Dysmsapi20180501.Client(config);
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.SDK.Dysmsapi20180501.Client client = CreateClient();
            // Create request object and set required input parameters
            AlibabaCloud.SDK.Dysmsapi20180501.Models.SendMessageToGlobeRequest sendMessageToGlobeRequest = new AlibabaCloud.SDK.Dysmsapi20180501.Models.SendMessageToGlobeRequest
            {   
                // Please replace with the actual recipient number.
                To = "<PHONE_NUMBER>",
                // Please replace with the actual SMS content.
                Message = "<YOUR_MESSAGE>",
            };
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                // Copy the code to run, please print the return value of the API by yourself.
                client.SendMessageToGlobeWithOptions(sendMessageToGlobeRequest, runtime);
            }
            catch (TeaException error)
            {
                // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
                // print error message
                Console.WriteLine(error.Message);
                // Please click on the link below for diagnosis.
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
                // Only a printing example. Please be careful about exception handling and do not ignore exceptions directly in engineering projects.
                // print error message
                Console.WriteLine(error.Message);
                // Please click on the link below for diagnosis.
                Console.WriteLine(error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
        }


    }
}

Special scenario: File upload through the Advance operation

When you use Image Search or Visual Intelligence API (VIAPI) to process images on an on-premises machine or upload images, the API of the Image Search or VIAPI described in the documentation does not support direct upload. To upload images, you need to use the Advance operation, which supports transmission of file streams. The cloud service temporarily stores the uploaded file in Object Storage Service (OSS), and reads the temporary file from OSS when necessary. The default region of OSS is cn-shanghai. The following example shows how to call the DetectBodyCount operation of VIAPI:

Note

Temporary files in OSS are regularly cleared.

  1. Initialize a request client

    Make sure that both the RegionId parameter and the endpoint of the cloud service are specified. RegionId indicates the OSS region in which the temporary files are stored. If you do not configure the RegionId parameter, the cloud service may use a different region than OSS, resulting in 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);
    }
  2. Create a request object

    Create the <API operation>AdvanceRequest request object to pass file streams. In the request object, set the parameter name to ImageURLObject.

    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.
        };   
  3. Initiate a request

    Call the <API operation name>Advance function to initiate a 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));

Click to view the complete sample code

// dotnet add package AlibabaCloud.SDK.Facebody20191230 --version 4.1.2

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
        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);
        }

        public static void Main(string[] args)
        {
            try
            {
                AlibabaCloud.SDK.Facebody20191230.Client client = CreateClient();
                // Replace <FILE_PATH> with the actual file path.
                using (FileStream fileStream = File.OpenRead(@"<FILE_PATH>"))
                {
                    AlibabaCloud.SDK.Facebody20191230.Models.DetectBodyCountAdvanceRequest detectBodyCountAdvanceRequest =
                        new AlibabaCloud.SDK.Facebody20191230.Models.DetectBodyCountAdvanceRequest
                        {
                            ImageURLObject = fileStream,
                        };
                    AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                    AlibabaCloud.SDK.Facebody20191230.Models.DetectBodyCountResponse response =
                        client.DetectBodyCountAdvance(detectBodyCountAdvanceRequest, runtime);
                    Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(response));
                }
            }
            catch (TeaException error)
            {
                // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only. 
                Console.WriteLine(error.Message);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(
                    new Dictionary<string, object> { { "message", _error.Message } }
                );
                // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only. 
                Console.WriteLine(error.Message);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
        }
    }
}

FAQ

  • How do I handle the "You are not authorized to perform this operation" error thrown by an API operation?

    Cause: The AccessKey pair used by the Resource Access Management (RAM) user does not have the permissions to call the API operation.

    Solution: Grant the required permissions to the RAM user. For more information, see Grant permissions to a RAM user.

    For example, if the "You are not authorized to perform this operation" error is thrown by the SendMessageToGlobe API operation, create the following custom policy to grant the required permissions to the RAM user:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendMessageToGlobe",
          "Resource": "*"
        }
      ]
    }
  • How do I handle the "System.UnretryableException: One or more errors occurred" error thrown by an API operation?

    Cause: The API operation does not support the endpoint that you specify when you initialize the request client.

    Solution: Specify a supported endpoint and try again. For more information, see Configure an endpoint.

  • 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 is not correctly passed to the request.

    Solution: Make sure that the AccessKey pair is correctly passed when you initialize the request client. Environment.GetEnvironmentVariable("XXX") indicates that the XXX value is obtained from the environment variable.

For more information about how to handle SDK errors, see FAQ.