Use ECS SDK V2.0 for .NET

Updated at:
Copy as MD

This topic describes how to install Elastic Compute Service (ECS) SDK V2.0 for .NET and provides an example on how to use the SDK to call ECS API operations. In the example, ECS SDK V2.0 for .NET is used to call the DescribeInstances operation to query information about ECS instances.

Prerequisites

  1. The AccessKey of an Alibaba Cloud account provides full access to your resources, which poses a high security risk if the AccessKey is leaked. We recommend that you create a Resource Access Management (RAM) user and grant the RAM user only the required permissions. Then, use the AccessKey of the RAM user to call API operations. For more information, see Create an AccessKey.

  2. You have granted the RAM user permissions to manage ECS resources. The example code in this topic shows a query operation. In this example, the AliyunECSReadonlyAccess system policy is used. You can grant custom permissions as needed.

    1. Use custom policies.

      For more information about how to create custom policies, see Create a custom policy and Authorization information.

      ECS provides custom policy examples based on best practices. You can use these examples to quickly create custom policies that meet your business needs. For more information, see Custom policies.

    2. Use system policies.

      For information about all system policies that ECS supports and their permission descriptions, see System policies for ECS.

  3. Configure the AccessKey using environment variables. For more information, see Configure environment variables on Linux, macOS, and Windows systems.

Install ECS SDK V2.0 for .NET

For information about how to install ECS SDK V2.0 for .NET, visit the SDK Center. You can use one of the following methods to install ECS SDK V2.0 for .NET:

.NET CLI

dotnet add package AlibabaCloud.SDK.Ecs20140526 --version 4.3.1

Package Manager

Install-Package AlibabaCloud.SDK.Ecs20140526 -Version 4.3.1

PackageReference

<PackageReference Include="AlibabaCloud.SDK.Ecs20140526" Version="4.3.1" />

Paket CLI

paket add AlibabaCloud.SDK.Ecs20140526 --version 4.3.1

F# Interactive

#r "nuget: AlibabaCloud.SDK.Ecs20140526, 4.3.1"

Use ECS SDK V2.0 for .NET

1. Initialize a client.

Alibaba Cloud SDKs support multiple access credentials, such as AccessKey pairs and Security Token Service (STS) tokens, to initialize clients. For more information, see Manage access credentials. In this example, an AccessKey pair is used to initialize a client.

namespace ecs
{
    public class Sample
    {
        static void Main(string[] args)
        {
            var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // Obtain the AccessKey ID from the environment variable. 
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey secret from the environment variable. 
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                Endpoint = "ecs.cn-hangzhou.aliyuncs.com"
            };
            var escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
        }
    }
}

2. Create a request object for the API operation.

Before you create a request object, view the parameters of the API operation that you want to call. In this example, the DescribeInstances operation is used. You can view the parameters of the DescribeInstances operation in DescribeInstances.

Note

The name of a request object is in the {Operation name}Request format. For example, the request object for the DescribeInstances operation is named DescribeInstancesRequest.

// Create a request object.
var describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeInstancesRequest
{
    RegionId = "cn-hangzhou"
};

3. Call the API operation.

When you call an API operation from a client, you can specify runtime parameters, such as timeout parameters and proxy parameters. For more information, see Advanced configuration.

Note

The name of a response object is in the {Operation name}Response format. For example, the response object for the DescribeInstances operation is named DescribeInstancesResponse.

// Create a runtime configuration object.
var runtimeOptions = new RuntimeOptions();
// Send the request.  
var describeInstancesResponse = escClient.DescribeInstancesWithOptions(describeInstancesRequest, runtimeOptions);

4. Handle exceptions.

SDK for .NET classifies exceptions into the following types:

  • TeaUnretryableException: This type of exception is caused by network issues. In most cases, a TeaUnretryableException exception is thrown when the maximum number of retries is reached. You can call the exception.getLastRequest method to obtain information about the API request when the exception occurs.

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

We recommend that you properly handle exceptions by performing operations, such as reporting exceptions, logging exceptions, and performing retries, to ensure the robustness and stability of your system.

5. Complete sample code.

using AlibabaCloud.TeaUtil.Models;
using Tea;

namespace ecs
{
    public class Sample
    {
        static void Main(string[] args)
        {
            var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
            {
                // Obtain the AccessKey ID from the environment variable. 
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey secret from the environment variable. 
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                Endpoint = "ecs.cn-hangzhou.aliyuncs.com"
            };

            var escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            
            // Create a request object.
            var describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeInstancesRequest
            {
                RegionId = "cn-hangzhou"
            };
            // Create a runtime configuration object.
            var runtimeOptions = new RuntimeOptions();
            try
            {
                // Send the request.  
                var describeInstancesResponse =
                    escClient.DescribeInstancesWithOptions(describeInstancesRequest, runtimeOptions);
                Console.WriteLine(describeInstancesResponse.ToMap());
            }
            catch (TeaUnretryableException error)
            {
                // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided only for reference. 
                Console.WriteLine(error);
            }
            catch (TeaException error)
            {
                // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided only for reference. 
                // Display error messages.
                Console.WriteLine(error.Message);
            }
            catch (Exception error)
            {
                // Handle exceptions with caution in actual business scenarios and do not ignore exceptions in your project. In this example, exceptions are provided only for reference. 
                Console.WriteLine(error);
            } 
        }
    }
}

References

You can also use ECS SDK V2.0 for .NET to perform generic calls to ECS API operations. For more information, see Generic calls.

If you use ECS SDK V1.0 for .NET, see V1.0 .NET SDK for information about the SDK.