The CMCC Cloud .Net SDK allows you to easily work with CMCC Cloud services such as Elastic Compute Service (ECS) and Virtual Private Cloud(VPC) without the need to handle API related tasks.
This document introduces how to obtain and use CMCC Cloud .Net SDK.
To use CMCC Cloud .NET SDK, you must have CMCC Cloud account as well as the Access Key (AK) and Secret key (SK) of the CMCC Cloud account. You can create an Access Key in the CMCC Cloud console.
To use CMCC Cloud .NET SDK to access the APIs of specific service, please make sure you do have activated the service in CMCC Cloud console if needed.
The .NET SDK requires:
Run the following commands to install .Net SDK:
You must install CMCCCloud.SDK.Core
library no matter which product development kit you need to use. Take using VPC
SDK for example, you need to install CMCCCloud.SDK.Core
library and CMCCCloud.SDK.Vpc
library:
dotnet add package CMCCCloud.SDK.Core
dotnet add package CMCCCloud.SDK.Vpc
Install-Package CMCCCloud.SDK.Core
Install-Package CMCCCloud.SDK.Vpc
{Service}Client
for VpcClient
in actual use.{your ak string}
, {your sk string}
, {your endpoint string}
and {your project id}
.using System;
using CMCCCloud.SDK.Core;
using CMCCCloud.SDK.Core.Auth;
// Import the specified {Service}, take Vpc as an example
using CMCCCloud.SDK.Vpc.V2;
using CMCCCloud.SDK.Vpc.V2.Model;
// Import the namespace for logging
using Microsoft.Extensions.Logging;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
const string ak = "{your ak string}";
const string sk = "{your sk string}";
const string endpoint = "{your endpoint string}";
const string projectId = "{your projectID string}";
Credentials auth = new BasicCredentials(ak, sk, projectId);
var config = HttpConfig.GetDefaultConfig();
config.IgnoreSslVerification = true;
VpcClient vpcClient = VpcClient.NewBuilder()
.WithCredential(auth)
.WithEndPoint(endpoint)
.WithHttpConfig(config)
.WithLogging(LogLevel.Information)
.Build();
var request = new ListVpcsRequest
{
Limit = 1
};
try
{
var response = vpcClient.ListVpcs(request);
Console.WriteLine(JsonUtils.Serialize(response.Vpcs));
}
catch (RequestTimeoutException requestTimeoutException)
{
Console.WriteLine(requestTimeoutException.ErrorMessage);
}
catch (ServiceResponseException serviceResponseException)
{
Console.WriteLine(serviceResponseException.HttpStatusCode);
Console.WriteLine(serviceResponseException.ErrorCode);
Console.WriteLine(serviceResponseException.ErrorMsg);
}
catch (ConnectionException connectionException)
{
Console.WriteLine(connectionException.ErrorMessage);
}
}
}
}
Detailed changes for each released version are documented in the CHANGELOG.md.
// Use default configuration
var config = HttpConfig.GetDefaultConfig();
Use network proxy if needed.
config.ProxyHost = "proxy.cmcccloud.com";
// assign proxy port
config.ProxyPort = 8080;
config.ProxyUsername = "test";
config.ProxyPassword = "test";
config.ProxyHost = "https://proxy.cmcccloud.com:8080";
config.ProxyUsername = "test";
config.ProxyPassword = "test";
// The default timeout is 120 seconds, which can be adjusted as needed
config.Timeout = 120;
// Skip SSL certifaction checking while using https protocal if needed
config.IgnoreSslVerification = true;
There are two types of CMCC Cloud services, regional
services and global
services.
Global services contain IAM, TMS, EPS.
For regional
services' authentication, projectId is required to initialize BasicCredentials.
For global
services' authentication, domainId is required to initialize GlobalCredentials.
Parameter description:
ak
is the access key ID for your account.sk
is the secret access key for your account.projectId
is the ID of your project depending on the region you want to operate.domainId
is the account ID of CMCC Cloud.securityToken
is the security token when using temporary AK/SK.You could use permanent AK and SK or use temporary AK and SK and SecurityToken to complete credentials' configuration.
// Regional services
Credentials basicCredentials = new BasicCredentials(ak, sk, projectId);
// Global services
Credentials globalCredentials = new GlobalCredentials(ak, sk, domainId);
It's required to obtain temporary AK&SK and security token first, which could be obtained through permanent AK&SK or through an agency.
CreateTemporaryAccessKeyByToken
in IAM SDK.// Regional services
Credentials basicCredentials = new BasicCredentials(ak, sk, projectId).WithSecurityToken(securityToken);
// Global services
Credentials globalCredentials = new GlobalCredentials(ak, sk, domainId).WithSecurityToken(securityToken);
There are two ways to initialize the {Service}Client, you could choose one you preferred.
// Specify the endpoint, take the endpoint of VPC service in region of cn-north-4 for example
String endpoint = "https://vpc.cidc-rp-11.joint.cmecloud.cn";
// Initialize the credentials, you should provide projectId or domainId in this way, take initializing BasicCredentials for example
Credentials basicCredentials = new BasicCredentials(ak, sk, projectId);
// Initialize specified {Service}Client instance, take initializing the regional service VPC's VpcClient for example
VpcClient vpcClient = VpcClient.NewBuilder()
.WithCredential(basicCredentials)
.WithEndPoint(endpoint)
.WithHttpConfig(config)
.Build();
// Send request and print response, take interface of ListVpcs for example
var request = new ListVpcsRequest
{
Limit = 1,
};
var response = vpcClient.ListVpcs(request)
Console.WriteLine(JsonUtils.Serialize(response.Vpcs));
Level 1 | Notice | Level 2 | Notice |
---|---|---|---|
ConnectionException | Connection error | HostUnreachableException | Host is not reachable |
SslHandShakeException | SSL certification error | ||
RequestTimeoutException | Request timeout | CallTimeoutException | timeout for single request |
RetryOutageException | no response after retrying | ||
ServiceResponseException | service response error | ServerResponseException | server inner error, http status code: [500,] |
ClientRequestException | invalid request, http status code: [400, 500) |
// Handle ClientRequestExceptions
try
{
var request = new ListVpcsRequest
{
Limit = 1,
};
var response = vpcClient.ListVpcs(request);
Console.WriteLine(JsonUtils.Serialize(response.Vpcs));
}
catch (ServiceResponseException serviceResponseException)
{
Console.WriteLine(serviceResponseException.HttpStatusCode);
Console.WriteLine(serviceResponseException.ErrorCode);
Console.WriteLine(serviceResponseException.ErrorMsg);
Console.WriteLine(serviceResponseException.RequestId);
}
// Initialize asynchronous client instance, take VpcAsyncClient for example
var vpcClient = VpcAsyncClient.NewBuilder()
.WithCredential(auth)
.WithEndPoint(endpoint)
.WithHttpConfig(config)
.Build();
// send asynchronous request
var future = vpcClient.ListVpcsAsync(new ListVpcsRequest()
{
Limit = 1
});
// get asynchronous response
var response = future.Result;
Console.WriteLine(JsonUtils.Serialize(response.Vpcs));
SDK supports Access
log and Debug
log which could be configured manually.
SDK supports print access log which could be enabled by manual configuration, the log could be output to the console.
For example:
var vpcClient = VpcClient.NewBuilder()
.WithCredential(auth)
.WithEndPoint(endpoint)
// configure log level and request will be print on the console
.WithLogging(LogLevel.Information)
.WithHttpConfig(config)
.Build();
After enabled log, the SDK will print the access log by default, every request will be recorded to the console like:
info: System.Net.Http.HttpClient.SdkHttpClient.LogicalHandler[100]
Start processing HTTP request GET https://vpc.cidc-rp-11.joint.cmecloud.cn/v1/076958154900d2492f8bc0197405c803/vpcs?limit=1
info: System.Net.Http.HttpClient.SdkHttpClient.ClientHandler[100]
Sending HTTP request GET https://vpc.cidc-rp-11.joint.cmecloud.cn/v1/076958154900d2492f8bc0197405c803/vpcs?limit=1
info: System.Net.Http.HttpClient.SdkHttpClient.ClientHandler[101]
Received HTTP response after 517.5326ms - OK
info: System.Net.Http.HttpClient.SdkHttpClient.LogicalHandler[101]
End processing HTTP request after 543.6428ms - OK
In some situation, you may need to debug your http requests, original http request and response information will be needed. The SDK provides a listener function to obtain the original encrypted http request and response information.
Warning: The original http log information is used in debugging stage only, please do not print the original http header or body in the production environment. These log information is not encrypted and contains sensitive data such as the password of your ECS virtual machine, or the password of your IAM user account, etc. When the response body is binary content, the body will be printed as "***" without detailed information.
private void RequestHandler(HttpRequestMessage message, ILogger logger)
{
logger.LogDebug(message.ToString());
}
private void ResponseHandler(HttpResponseMessage message, ILogger logger)
{
logger.LogDebug(message.ToString());
}
var vpcClient = VpcClient.NewBuilder()
.WithCredential(auth)
.WithEndPoint(endpoint)
.WithLogging(LogLevel.Debug)
.WithHttpConfig(config)
.WithHttpHandler(new HttpHandler()
.AddRequestHandler(RequestHandler)
.AddResponseHandler(ResponseHandler))
.Build();
where:
HttpHandler supports method AddRequestHandler
and AddResponseHandler
.
Use .Net Framework 4.7 to integrate .Net SDK, a dead lock occurs
[Symptom]: When using synchronized client to call an interface, and the program has been started, but where is no error message or timeout occurs.
[Cause]: The inner implementation of sending requests in synchronized client of SDK is to use an asynchronous task, and SDK will await this task. In such scenario, deadlock occurs between the context of the .Net Framework UI and the asynchronous task context of the SDK. As a result, the asynchronous task of the SDK cannot be activated. Original article
[Solution]: Switch the synchronous client to the asynchronous client. If the UI events and API requests are both asynchronous, there will be no deadlock.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。