Migrate from V1.0 SDK to V2.0 SDK
When you migrate existing .NET applications from V1.0 SDK to V2.0 SDK, you need to update dependency packages, client initialization, and API call code. This topic compares the usage of both versions and describes how to migrate, as well as the configuration differences for timeouts, HTTPS, proxies, retries, and exception handling.
Scope
This topic is intended for developers who use V1.0 .NET SDK. V1.0 and V2.0 refer to SDK architecture versions, not NuGet package version numbers.
Before you run the code examples in the "Migration details" section of this topic, install the .NET SDK and configure credentials. To configure credentials, see Managing access credentials. The identity used to call API operations must also have the required permissions.
V1.0 SDK will be phased out of maintenance, and no further feature updates or bug fixes will be provided. V2.0 SDK is under continuous maintenance and iteration. We strongly recommend that you complete the migration as soon as possible to obtain better feature support and long-term assurance.
Key changes in V2.0 SDK
V2.0 SDK is generated by the domain-specific language (DSL) Darabonba. The key changes are as follows:
V1.0 SDK relies on SDK Core (aliyun-net-sdk-core) to handle OpenAPI requests. V2.0 SDK expresses parameter handling, request assembly, and response processing logic through DSL, and no longer depends on the V1.0 SDK Core package.
Business parameters are separated from runtime parameters. Business parameters are set through the
Requestobject. You can directly initialize the object without calling a separate function to generate it. Parameters such as timeouts and proxies are set throughRuntimeOptions.Each cloud service SDK provides an independent
Client. You can configure credentials, regions, timeouts, proxies, and retry parameters separately for each service to avoid mixing client configurations across services.
Migration details
During migration, you need to update dependency packages, client initialization, and API call code, and review existing runtime configurations. The following examples primarily use Elastic Compute Service (ECS).
Each example is used independently. Examples that contain a Main method demonstrate the complete program structure. Examples that contain only a CreateClient method or configuration statements are code snippets that need to be placed in an existing project. Replace angle-bracket placeholders before running, and do not merge the Main methods from multiple examples.
SDK dependencies
V1.0 SDK
V1.0 cloud service SDKs provide Request, Response, and response deserialization objects. The main logic for OpenAPI requests is centralized in SDK Core, including credentials, HTTP requests, authentication information, signature algorithms, and exception handling. The following example uses ECS. Run the following commands in your project directory:
# Handles credentials, HTTP requests to OpenAPI, authentication, signature algorithms, and exception handling
dotnet add package aliyun-net-sdk-core
# Cloud service SDK, naming convention: aliyun-net-sdk-${service_name}
dotnet add package aliyun-net-sdk-ecsV2.0 SDK
V2.0 cloud service SDKs contain the parameter handling, request assembly, and response processing logic for each API operation, achieving decoupling from the V1.0 SDK Core package. When using a cloud service SDK, you only need to focus on the SDK package dependency of the cloud service itself. The following example uses ECS:
dotnet add package AlibabaCloud.SDK.Ecs20140526Configure clients and requests
Initialize the client
V1.0 SDK
V1.0 SDK uses DefaultAcsClient from SDK Core to handle requests for different services. Pass in the region configuration and credentials during initialization. For more information about endpoint configuration, see Configure endpoints.
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Auth;
namespace AlibabaCloud.SDK.Sample
{
class Program
{
static void Main(string[] args)
{
AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Pass in the region configuration and credentials.
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou");
DefaultAcsClient client = new DefaultAcsClient(profile, provider);
}
}
}The single-client pattern is not thread-safe, and sharing one profile across different services easily leads to permission management issues. We strongly recommend that you migrate to V2.0 SDK.
V2.0 SDK
V2.0 SDK supports two call methods: specialized calls and generic calls. The client is initialized differently for each method:
Specialized call: Each service maintains its own
Client, so services do not affect each other. Identical configurations can still be shared, for exampleconfig.Credential = 'points to the same CredentialsClient'.// Client initialization method snippet; called by the consumer via CreateClient. using System; namespace AlibabaCloud.SDK.Sample { public class Sample { public static AlibabaCloud.SDK.Ecs20140526.Client CreateClient() { Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client(); AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { Credential = credential, }; config.Endpoint = "ecs.cn-hangzhou.aliyuncs.com"; return new AlibabaCloud.SDK.Ecs20140526.Client(config); } } }Generic call: You do not need to install a service SDK (for example,
AlibabaCloud.SDK.Ecs20140526), but you must install the core libraryAlibabaCloud.OpenApiClientand useAlibabaCloud.OpenApiClient.Clientto configure API information manually. The following example uses the Credentials tool to initialize credentials. For more information, see Manage credentials.dotnet add package AlibabaCloud.OpenApiClient// Client initialization method snippet; called by the consumer via CreateClient. using System; namespace AlibabaCloud.SDK.Sample { public class Sample { public static AlibabaCloud.OpenApiClient.Client CreateClient() { Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client(); AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { Credential = credential, }; config.Endpoint = "ecs.cn-hangzhou.aliyuncs.com"; return new AlibabaCloud.OpenApiClient.Client(config); } } }
After the client is initialized, use the methods of the cloud service client or the CallApi method of the generic client to send requests. You do not need to dispose of the client object manually, because it is reclaimed automatically by the garbage collector.
When different services use different credentials, initialize separate clients to avoid configuration conflicts. Do not modify shared configuration objects during request execution.
Configure endpoints
An endpoint is the service access domain name of an OpenAPI operation, such as ecs.cn-hangzhou.aliyuncs.com. Select an endpoint that matches the target service, region, and network type.
After you complete the endpoint configuration migration, make sure that you carefully verify whether the endpoint addresses of V1.0 and V2.0 are exactly the same. If they differ, API calls may fail or requests may be routed incorrectly.
V1.0 SDK
V1.0 SDK applies endpoint configuration methods in the following order of decreasing priority: custom endpoint > endpoint resolution by the cloud service SDK > endpoint resolution by SDK Core > endpoint resolution by the Location service.
Custom endpoint:
This method has the highest priority and takes effect only for the current request. Call
request.SetEndpoint.using System; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Profile; using Aliyun.Acs.Core.Auth; using Aliyun.Acs.Ecs.Model.V20140526; namespace AlibabaCloud.SDK.Sample { class Program { static void Main(string[] args) { AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider( Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou"); DefaultAcsClient client = new DefaultAcsClient(profile, provider); var request = new DescribeRegionsRequest(); request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS; // Takes effect only for the current request. request.SetEndpoint("<Endpoint>"); var response = client.GetAcsResponse(request); Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content)); } } }This method takes effect globally and supports adding multiple endpoints. Call
profile.AddEndpointto add mappings by service and region.using System; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Profile; using Aliyun.Acs.Core.Auth; using Aliyun.Acs.Ecs.Model.V20140526; namespace AlibabaCloud.SDK.Sample { class Program { static void Main(string[] args) { AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider( Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou"); // Takes effect globally. profile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Ecs", "ecs.cn-hangzhou.aliyuncs.com"); // Add endpoint mappings for other services and regions as needed. DefaultAcsClient client = new DefaultAcsClient(profile, provider); var request = new DescribeRegionsRequest(); request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS; var response = client.GetAcsResponse(request); Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content)); } } }
Endpoint resolution by the cloud service SDK.
When no custom endpoint is set, if the cloud service has a built-in endpoint file (for example, Endpoint.cs for ECS), endpoints are resolved by the following logic:
Public network requests are preferred: If the network access method of the service is public (
request.ProductNetwork = "public", which is the default value) and the endpoint file contains the specifiedRegionId, the SDK automatically resolves the endpoint from the built-in endpoint mapping of the cloud service SDK based on the RegionId.If ProductNetwork is not public, or the specified RegionId does not exist in the built-in endpoint mapping, the endpoint is automatically assembled according to rules:
[product_code][-suffix]?[-productNetwork]?.[region_id]?.aliyuncs.com, where whether the bracketed parts appear depends on the endpoint resolution rules of the service.
using System; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Profile; using Aliyun.Acs.Core.Auth; using Aliyun.Acs.Ecs.Model.V20140526; namespace AlibabaCloud.SDK.Sample { class Program { static void Main(string[] args) { AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider( Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // Set the region ID. "cn-shanghai" is used as an example. IClientProfile profile = DefaultProfile.GetProfile("cn-shanghai"); DefaultAcsClient client = new DefaultAcsClient(profile, provider); var request = new DescribeRegionsRequest(); request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS; // Set the network access type. The default value "public" indicates Internet access. // Other network types include share, ipv6, proxy, inner, dualstack, and vpc. Verify that the target service supports the type. request.ProductNetwork = "public"; // When using VPC access, you can also configure the following option based on service support. // profile.EnableUsingVpcEndpoint(); var response = client.GetAcsResponse(request); Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content)); } } }Endpoint resolution by SDK Core.
If the cloud service SDK does not provide a built-in endpoint mapping, endpoints are resolved based on
RegionIdfrom endpoints.json in SDK Core: the service-specific endpoints are searched first; if no match is found, theglobal endpointsare searched based on theproductCodeof the service.Call the Location service for endpoint resolution.
NoteNot all cloud services support this resolution mode. We recommend that you use a custom endpoint instead.
When SDK Core still cannot find an endpoint, it calls the Location service using
serviceCodeandregionId.serviceCode: Provided by theRequestobject of the cloud service SDK. No manual configuration is required.regionId: The region ID specified when initializing the client.
V2.0 SDK
Not all cloud service SDKs support automatic endpoint resolution based on RegionId. When you are unsure whether a service supports automatic resolution, configure a custom endpoint.
V2.0 SDK supports only custom endpoint configuration. The priority order from high to low is: custom endpoint (Config.Endpoint) > custom RegionId (Config.RegionId).
Custom endpoint: Set
Config.Endpointwhen you initialize the client. You can find the service endpoint domain name on the product page of the OpenAPI Developer Portal.// Client initialization method snippet; called by the consumer via CreateClient. using System; namespace AlibabaCloud.SDK.Sample { public class Sample { public static AlibabaCloud.SDK.Ecs20140526.Client CreateClient() { Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client(); AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { Credential = credential, }; // Set the endpoint. Refer to the service endpoint list for the correct domain name. config.Endpoint = "ecs.cn-hangzhou.aliyuncs.com"; return new AlibabaCloud.SDK.Ecs20140526.Client(config); } } }Custom
RegionId:If the
Clientof the cloud service contains a mapping object betweenRegionIdand endpoints named_endpointMap(for example, Client.cs), the corresponding endpoint is obtained from that object based on the RegionId.If the
Clientof the cloud service does not contain that object, or the specifiedRegionIdhas no corresponding endpoint mapping in that object, the endpoint is automatically assembled according to the assembly rules.
// Client initialization method snippet; called by the consumer via CreateClient. using System; namespace AlibabaCloud.SDK.Sample { public class Sample { public static AlibabaCloud.SDK.Ecs20140526.Client CreateClient() { Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client(); AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { Credential = credential, }; // Custom RegionId. The SDK resolves the corresponding endpoint. config.RegionId = "cn-hangzhou"; return new AlibabaCloud.SDK.Ecs20140526.Client(config); } } }
Advanced configuration
HTTPS configuration
When you call OpenAPI operations over HTTPS, the SDK verifies SSL/TLS certificates by default. If the environment lacks trusted certificates, certificate verification may fail. To ensure communication security in production environments, we recommend that you keep certificate verification enabled.
Disabling certificate verification removes server identity authentication and exposes the connection to man-in-the-middle attacks. The following configurations for ignoring certificate verification are limited to isolated test environments and must not be used in production.
V1.0 SDK
Specify HTTPS through the Request object's Protocol property. The following is a request configuration snippet:
// Request configuration snippet: request is an existing Request object.
request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS;If you must ignore certificate verification in an isolated test environment, use the following configuration snippet. We strongly recommend that you keep certificate verification enabled in production environments.
// For isolated test environments only; client and request are existing objects.
// Client-level configuration.
client.SetHttpsInsecure(true);
// Request-level configuration.
request.SetHttpsInsecure(true);V2.0 SDK
V2.0 SDK determines the request protocol for OpenAPI operations in the following order of decreasing priority: the Config setting > the default value. Set the request protocol of the client through Config.Protocol. When it is not set, the protocol type supported by default by the OpenAPI operation (HTTPS) is used. The following example explicitly sets HTTPS.
using System;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Ecs20140526.Models;
class Sample
{
static void Main(string[] args)
{
Config config = new Config
{
Credential = new Aliyun.Credentials.Client(),
Endpoint = "ecs.cn-hangzhou.aliyuncs.com"
};
config.Protocol = "HTTPS";
AlibabaCloud.SDK.Ecs20140526.Client client = new AlibabaCloud.SDK.Ecs20140526.Client(config);
DescribeInstancesRequest request = new DescribeInstancesRequest
{
RegionId = "cn-hangzhou"
};
var response = client.DescribeInstances(request);
Console.WriteLine(response.Body.TotalCount);
}
}If you must ignore certificate verification in an isolated test environment, set RuntimeOptions.IgnoreSSL of the current request to true. We strongly recommend that you keep certificate verification enabled in production environments.
using System;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Ecs20140526.Models;
using AlibabaCloud.TeaUtil.Models;
class Sample
{
static void Main(string[] args)
{
Config config = new Config
{
Credential = new Aliyun.Credentials.Client(),
Endpoint = "ecs.cn-hangzhou.aliyuncs.com"
};
config.Protocol = "HTTPS";
AlibabaCloud.SDK.Ecs20140526.Client client = new AlibabaCloud.SDK.Ecs20140526.Client(config);
// For isolated test environments only; do not set IgnoreSSL = true in production.
RuntimeOptions runtime = new RuntimeOptions
{
IgnoreSSL = true
};
DescribeInstancesRequest request = new DescribeInstancesRequest
{
RegionId = "cn-hangzhou"
};
var response = client.DescribeInstancesWithOptions(request, runtime);
Console.WriteLine(response.Body.TotalCount);
}
}Proxy configuration
V1.0 SDK
V1.0 SDK preferentially uses the proxy address configured in the client. When no proxy is configured, it reads proxy environment variables.
The following proxy environment variables are supported:
HTTP_PROXYorhttp_proxy: The proxy address for HTTP requests.HTTPS_PROXYorhttps_proxy: The proxy address for HTTPS requests.NO_PROXYorno_proxy: Addresses that bypass the proxy.
Client-level proxy configuration example:
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Auth;
namespace AlibabaCloud.SDK.Sample
{
class Program
{
static void Main(string[] args)
{
// Configure AccessKey environment variables before running.
AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou");
DefaultAcsClient client = new DefaultAcsClient(profile, provider);
// Client-level proxy configuration takes precedence over environment variables.
// Set the HTTP request proxy.
client.SetHttpProxy("http://localhost:8080");
// Get the HTTP request proxy.
client.GetHttpProxy();
// Set the HTTPS request proxy.
client.SetHttpsProxy("https://localhost:8080");
// When the proxy requires authentication, replace the previous line with the following configuration.
// client.SetHttpsProxy("http://<username>:<password>@localhost:8080");
// Get the HTTPS request proxy.
client.GetHttpsProxy();
// Set addresses that bypass the proxy.
client.SetNoProxy("example.com");
// Get addresses that bypass the proxy.
client.GetNoProxy();
}
}
}V2.0 SDK
V2.0 SDK preferentially uses the proxy configuration in RuntimeOptions for the request, followed by the client-level proxy configuration in Config.
Request-level configuration: Set the proxy used by the current request through
RuntimeOptions.using System; using AlibabaCloud.TeaUtil.Models; namespace demo { public class Sample { static void Main(string[] args) { var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config { // Get the AccessKey ID from environment variables. AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Get the AccessKey Secret from environment variables. AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), Endpoint = "ecs.cn-beijing.aliyuncs.com" }; var ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig); var describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest(); // Runtime configuration takes effect only for calls that use this object. var runtimeOptions = new RuntimeOptions(); runtimeOptions.HttpProxy = "http://127.0.0.1:9898"; runtimeOptions.HttpsProxy = "http://<username>:<password>@127.0.0.1:8989"; runtimeOptions.NoProxy = "127.0.0.1,localhost"; var response = ecsClient.DescribeRegionsWithOptions(describeRegionsRequest, runtimeOptions); Console.WriteLine(response.Body.ToMap()); } } }Client-level configuration: Set the proxy used by the client through
Config.using System; using AlibabaCloud.TeaUtil.Models; namespace demo { public class Sample { static void Main(string[] args) { var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config { // Get the AccessKey ID from environment variables. AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), // Get the AccessKey Secret from environment variables. AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), Endpoint = "ecs.cn-beijing.aliyuncs.com", // Client-level proxy configuration. NoProxy = "127.0.0.1,localhost", HttpProxy = "http://127.0.0.1:9898", HttpsProxy = "http://<username>:<password>@127.0.0.1:8989" }; var ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig); var describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest(); var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); var response = ecsClient.DescribeRegionsWithOptions(describeRegionsRequest, runtime); Console.WriteLine(response.Body.ToMap()); } } }
Timeout configuration
V1.0 SDK
V1.0 SDK applies timeout settings in the following order of decreasing priority: the Request setting > the Client setting > the default configuration. The default connection timeout is 5 seconds, and the default read timeout is 10 seconds. The following example explicitly sets timeouts at both levels, in milliseconds.
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Auth;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Ecs.Model.V20140526;
class Sample
{
static void Main(string[] args)
{
AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou");
DefaultAcsClient client = new DefaultAcsClient(profile, provider);
// Client-level timeout, in milliseconds.
client.SetConnectTimeoutInMilliSeconds(1024);
client.SetReadTimeoutInMilliSeconds(2048);
// Request-level settings take precedence over client-level settings.
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.RegionId = "cn-hangzhou";
request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS;
request.SetConnectTimeoutInMilliSeconds(1024);
request.SetReadTimeoutInMilliSeconds(2048);
DescribeInstancesResponse response = client.GetAcsResponse(request);
Console.WriteLine(response.TotalCount);
}
}V2.0 SDK
To avoid confusion, V2.0 SDK separates runtime parameters such as timeout settings from business parameters. Timeout settings are applied in the following order of decreasing priority: the RuntimeOptions setting of the request > the Config setting of the client > the default configuration. The default connection timeout is 5 seconds, and the default read timeout is 10 seconds, in milliseconds.
using System;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Ecs20140526.Models;
using AlibabaCloud.TeaUtil.Models;
class Sample
{
static void Main(string[] args)
{
Config config = new Config
{
Credential = new Aliyun.Credentials.Client(),
Endpoint = "ecs.cn-hangzhou.aliyuncs.com"
};
// Client-level timeout, in milliseconds.
config.ConnectTimeout = 1024;
config.ReadTimeout = 2048;
AlibabaCloud.SDK.Ecs20140526.Client client = new AlibabaCloud.SDK.Ecs20140526.Client(config);
// Request-level settings take precedence over client-level settings.
RuntimeOptions runtime = new RuntimeOptions
{
ConnectTimeout = 1024,
ReadTimeout = 2048
};
DescribeInstancesRequest request = new DescribeInstancesRequest
{
RegionId = "cn-hangzhou"
};
var response = client.DescribeInstancesWithOptions(request, runtime);
Console.WriteLine(response.Body.TotalCount);
}
}Retry mechanism
Neither version performs retries by default. After you migrate to V2.0 SDK, if you need the retry capability, enable it through RuntimeOptions.
V1.0 SDK
V1.0 SDK does not provide a retry mechanism.
V2.0 SDK
Tea-based V2.0 SDK retries OpenAPI requests that encounter network problems, but does not retry business errors. Retries are enabled through runtime parameters in the request, in the following order of decreasing priority: RuntimeOptions > the default value. Retries are disabled by default. If you enable retries without specifying the number of attempts, a maximum of 3 retries are performed by default. The following example enables automatic retry through RuntimeOptions.Autoretry and sets MaxAttempts to 3.
using System;
using AlibabaCloud.TeaUtil.Models;
namespace demo
{
public class Sample
{
static void Main(string[] args)
{
var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
{
// Get the AccessKey ID from environment variables.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Get the AccessKey Secret from environment variables.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
Endpoint = "ecs.cn-beijing.aliyuncs.com"
};
var ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
var describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
// Runtime configuration takes effect only for calls that use this object.
var runtimeOptions = new RuntimeOptions();
// Enable automatic retry.
runtimeOptions.Autoretry = true;
// Set the MaxAttempts parameter.
runtimeOptions.MaxAttempts = 3;
var response = ecsClient.DescribeRegionsWithOptions(describeRegionsRequest, runtimeOptions);
Console.WriteLine(response.Body.ToMap());
}
}
}Call OpenAPI operations
Specialized SDK OpenAPI calls
V1.0 SDK
All OpenAPI requests are handled uniformly by SDK Core. The cloud service SDK provides the Request and Response objects for OpenAPI operations. The following examples show how to call OpenAPI operations:
The following example calls the DescribeRegions operation of ECS to query available regions. This is a read-only operation.
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Auth;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Ecs.Model.V20140526;
namespace AlibabaCloud.SDK.Sample
{
class Program
{
static void Main(string[] args)
{
AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou");
DefaultAcsClient client = new DefaultAcsClient(profile, provider);
// Instantiate the DescribeRegionsRequest object.
var request = new DescribeRegionsRequest();
// SDK Core performs the actual HTTP request and serializes the returned result into the SDK Response object.
var response = client.GetAcsResponse(request);
Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
}
}
}V2.0 SDK
The cloud service SDK provides the Request and Response objects for OpenAPI operations, and calls are initiated through the Client of the service.
Create a Request object for the corresponding API operation and call the method in the Client. The API version, the RPC or ROA style, and the HTTP method are encapsulated by the service SDK, so you do not need to handle them.
using System;
using Newtonsoft.Json;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.SDK.Ecs20140526.Client CreateClient()
{
Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client();
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
Credential = credential,
};
config.Endpoint = "ecs.cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.SDK.Ecs20140526.Client(config);
}
public static void Main(string[] args)
{
AlibabaCloud.SDK.Ecs20140526.Client client = CreateClient();
AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse resp = client.DescribeRegionsWithOptions(describeRegionsRequest, runtime);
Console.WriteLine(JsonConvert.SerializeObject(resp, Formatting.Indented));
}
}
}CommonRequest calls
V1.0 SDK: CommonRequest
CommonRequest is used for generic calls that do not depend on cloud service request models. You need to set the following information:
Domain: The service endpoint domain name.Version: The API version in YYYY-MM-DD format.API information: Set
ActionorUriPatternbased on the API style.RPC style (for example, ECS and RDS): Use
Actionto specify the operation name, for example,request.Action = "<Action>".ROA style (RESTful, for example, Container Service): Use
UriPatternto specify the request path, for example,request.UriPattern = "<UriPattern>".
RPC example: Query ECS instance status.
using System.Collections.Generic;
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
class Sample
{
static void Main(string[] args)
{
// Initialize the client.
IClientProfile profile = DefaultProfile.GetProfile(
// Region ID
"cn-hangzhou",
// Read the AccessKey ID from environment variables.
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Read the AccessKey Secret from environment variables.
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
DefaultAcsClient client = new DefaultAcsClient(profile);
try
{
// Construct the request.
CommonRequest request = new CommonRequest();
request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS;
request.Domain = "ecs.aliyuncs.com";
request.Version = "2014-05-26";
// For RPC-style APIs, specify the operation name through Action.
request.Action = "DescribeInstanceStatus";
request.AddQueryParameters("RegionId", "cn-hangzhou");
List<string> instanceIds = new List<string> { "i-bp124uve8zq7XXXXXXXX", "i-bp1axhql4dqaXXXXXXXX" };
for (int i = 0; i < instanceIds.Count; i++)
{
request.AddQueryParameters($"InstanceId.{i + 1}", instanceIds[i]);
}
request.AddQueryParameters("PageNumber", "1");
request.AddQueryParameters("PageSize", "30");
// Send the request and get the response.
CommonResponse response = client.GetCommonResponse(request);
System.Console.WriteLine(response.Data);
}
catch (ServerException ex)
{
System.Console.WriteLine(ex.ToString());
}
catch (ClientException ex)
{
System.Console.WriteLine(ex.ToString());
}
}
}ROA example: Query Container Service clusters.
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
class Sample
{
static void Main(string[] args)
{
// Initialize the client.
IClientProfile profile = DefaultProfile.GetProfile(
// Region ID
"<REGION-ID>",
// Read the AccessKey ID from environment variables.
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Read the AccessKey Secret from environment variables.
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
DefaultAcsClient client = new DefaultAcsClient(profile);
try
{
// Construct the request.
CommonRequest request = new CommonRequest();
request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS;
request.Domain = "cs.aliyuncs.com";
request.Version = "2015-12-15";
// For ROA-style APIs, specify the request path through UriPattern.
request.UriPattern = "/clusters";
// Send the request and get the response.
CommonResponse response = client.GetCommonResponse(request);
System.Console.WriteLine(response.Data);
}
catch (ServerException ex)
{
System.Console.WriteLine(ex.ToString());
}
catch (ClientException ex)
{
System.Console.WriteLine(ex.ToString());
}
}
}V2.0 SDK: CallApi
Configure the basic information of the OpenAPI operation through AlibabaCloud.OpenApiClient.Models.Params, such as the API style, the API version, and the request method. Call CallApi through AlibabaCloud.OpenApiClient.Client to initiate the request. The following example shows how to set Params:
Parameters | Description | Examples |
| The API style. | RPC |
| The API version. | 2014-05-26 |
| The HTTP request method. | POST |
| The operation name. | DescribeRegions |
| The request path. | / |
| The request protocol. | HTTPS |
| The authentication type. | AK |
| The request body format. | json |
| The response body format. | json |
Complete example: Use AlibabaCloud.OpenApiClient.Models.Params to set the API information, and call the DescribeRegions operation of ECS through the CallApi method of AlibabaCloud.OpenApiClient.Client.
using System;
using Newtonsoft.Json;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.OpenApiClient.Client CreateClient()
{
Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client();
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
Credential = credential,
};
config.Endpoint = "ecs.cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.OpenApiClient.Client(config);
}
public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
{
AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
{
// Operation name.
Action = "DescribeRegions",
// API version.
Version = "2014-05-26",
// Request protocol.
Protocol = "HTTPS",
// HTTP request method.
Method = "POST",
AuthType = "AK",
Style = "RPC",
// Request path.
Pathname = "/",
// Request body format.
ReqBodyType = "json",
// Response body format.
BodyType = "json",
};
return params_;
}
public static void Main(string[] args)
{
AlibabaCloud.OpenApiClient.Client client = CreateClient();
AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest();
// The returned dictionary contains body, headers, and statusCode.
object resp = client.CallApi(params_, request, runtime);
Console.WriteLine(JsonConvert.SerializeObject(resp, Formatting.Indented));
}
}
}RPC example: Call DescribeInstanceTypeFamilies to query ECS instance type families.
using System.Collections.Generic;
using System;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.OpenApiClient.Client CreateClient()
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
config.Endpoint = "ecs.cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.OpenApiClient.Client(config);
}
public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
{
AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
{
// Operation name.
Action = "DescribeInstanceTypeFamilies",
// API version.
Version = "2014-05-26",
// Request protocol.
Protocol = "HTTPS",
// HTTP request method.
Method = "POST",
AuthType = "AK",
Style = "RPC",
// Request path.
Pathname = "/",
// Request body format.
ReqBodyType = "json",
// Response body format.
BodyType = "json",
};
return params_;
}
public static void Main(string[] args)
{
AlibabaCloud.OpenApiClient.Client client = CreateClient();
AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
// Query parameters.
Dictionary<string, object> queries = new Dictionary<string, object>();
queries["RegionId"] = "cn-hangzhou";
// Runtime parameters.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
{
Query = AlibabaCloud.OpenApiUtil.Client.Query(queries),
};
// Read the API response.
// The returned dictionary contains body, headers, and statusCode.
var response = client.CallApi(params_, request, runtime);
Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
}
}
}ROA example: Call DescribeClustersV1 to query Container Service clusters.
using System;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
public static AlibabaCloud.OpenApiClient.Client CreateClient()
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
config.Endpoint = "cs.cn-hangzhou.aliyuncs.com";
return new AlibabaCloud.OpenApiClient.Client(config);
}
public static AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
{
AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
{
// Operation name.
Action = "DescribeClustersV1",
// API version.
Version = "2015-12-15",
// Request protocol.
Protocol = "HTTPS",
// HTTP request method.
Method = "GET",
AuthType = "AK",
Style = "ROA",
// Request path.
Pathname = "/api/v1/clusters",
// Request body format.
ReqBodyType = "json",
// Response body format.
BodyType = "json",
};
return params_;
}
public static void Main(string[] args)
{
AlibabaCloud.OpenApiClient.Client client = CreateClient();
AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();
// Runtime parameters.
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest();
// Read the API response.
// The returned dictionary contains body, headers, and statusCode.
var response = client.CallApi(params_, request, runtime);
Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
}
}
}Exception handling
V1.0 SDK
Catch ServerException and ClientException, and read ErrorCode, ErrorMessage, and RequestId. When a request does not reach the server, the exception may not contain a RequestId.
using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Ecs.Model.V20140526;
namespace AlibabaCloud.SDK.Sample
{
class Program
{
static void Main(string[] args)
{
// Initialize the client.
IClientProfile profile = DefaultProfile.GetProfile(
// Region ID
"your-region-id",
// Read the AccessKey ID from environment variables.
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Read the AccessKey Secret from environment variables.
Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
DefaultAcsClient client = new DefaultAcsClient(profile);
try
{
// Construct the request.
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.Protocol = Aliyun.Acs.Core.Http.ProtocolType.HTTPS;
request.PageSize = 10;
// Send the request and get the response.
DescribeInstancesResponse response = client.GetAcsResponse(request);
System.Console.WriteLine(response.TotalCount);
}
catch (ServerException e)
{
System.Console.WriteLine(e.ToString());
// Handle exceptions based on your business requirements.
// For example, print the detailed error information.
Console.WriteLine("ErrorCode=" + e.ErrorCode);
Console.WriteLine("ErrorMessage=" + e.ErrorMessage);
// Provide the RequestId when submitting a ticket.
Console.WriteLine("RequestId=" + e.RequestId);
}
catch (ClientException ex)
{
System.Console.WriteLine(ex.ToString());
// Handle exceptions based on your business requirements.
// For example, print the detailed error information.
Console.WriteLine("ErrorCode=" + ex.ErrorCode);
Console.WriteLine("ErrorMessage=" + ex.ErrorMessage);
}
}
}
}V2.0 SDK
Tea-based V2.0 SDK uses the following exception types. The property descriptions below use Tea 1.1.4 as an example:
TeaUnretryableException: Thrown when a request cannot be retried. Use theLastRequestproperty to view the last request, andInnerExceptionto view the cause.TeaException: Used to convey API error information. Common properties:Code: The error code.Message: The error message. The error message returned by the API operation contains aRequestId.DataResult: The detailed error information returned by the server. Before reading fields from this object, verify that the object and fields exist.
using System;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Ecs20140526.Models;
using AlibabaCloud.TeaUtil.Models;
using Tea;
class Sample
{
static void Main(string[] args)
{
Config config = new Config
{
Credential = new Aliyun.Credentials.Client(),
Endpoint = "ecs.cn-hangzhou.aliyuncs.com"
};
AlibabaCloud.SDK.Ecs20140526.Client client = new AlibabaCloud.SDK.Ecs20140526.Client(config);
DescribeInstancesRequest request = new DescribeInstancesRequest
{
RegionId = "cn-hangzhou"
};
RuntimeOptions runtime = new RuntimeOptions();
try
{
client.DescribeInstancesWithOptions(request, runtime);
}
catch (TeaUnretryableException error)
{
Console.WriteLine(error.Message);
// LastRequest may contain sensitive information. Do not print the entire request directly.
if (error.InnerException != null)
{
Console.WriteLine(error.InnerException.Message);
}
}
catch (TeaException error)
{
Console.WriteLine("Code=" + error.Code);
Console.WriteLine("Message=" + error.Message);
object requestId;
if (error.DataResult != null && error.DataResult.TryGetValue("RequestId", out requestId))
{
Console.WriteLine("RequestId=" + requestId);
}
object recommend;
if (error.DataResult != null && error.DataResult.TryGetValue("Recommend", out recommend))
{
Console.WriteLine("Recommend=" + recommend);
}
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
}
}Technical support
If you encounter issues when using the SDK, you can get technical support through the following channels:
Submit a ticket: Go to the Alibaba Cloud ticket submission page.
Feature requests or issue feedback: Join the DingTalk group (group ID: 31875811) to contact technical support.