Generalized calls

更新时间:
复制 MD 格式

The Alibaba Cloud SDK V1.0 supports a universal method, known as a generalized call, for calling OpenAPI. This topic describes how to use generalized calls to access OpenAPI.

Features

  • Lightweight: You only need the Core package to make calls. You do not need to download and install the SDKs for each product.

  • High compatibility: You can use generalized calls when a cloud product does not yet provide an SDK, or when a new API is released but the SDK is not updated. This lets you call the latest API operations without waiting for SDK updates.

For more information, see Generalized calls and specialized calls.

Usage notes

Before you use generalized calls, you must manually obtain and configure OpenAPI metadata, such as the version number, the URI of the request, and parameter types. For more information about the API style, request parameters, and resource paths of an OpenAPI, see OpenAPI metadata.

Install the core SDK

Run the following command in the terminal to install the core SDK. For the latest version, see aliyun-net-sdk-core.

dotnet add package aliyun-net-sdk-core

Call an OpenAPI

Initialize a request client

Create a DefaultAcsClient object to initialize the request client. This example shows how to use an AccessKey to initialize the client. For more information about other initialization methods, see Manage access credentials.

Note

To prevent credential leaks, store the credentials in environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.

using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
        public static void Main(string[] args)
        {
            IClientProfile profile = DefaultProfile.GetProfile(
                // The region ID.
                "<REGION_ID>",
                // Obtain the AccessKey ID of the Resource Access Management (RAM) user from an environment variable.
                Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey secret of the RAM user from an environment variable.
                Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            DefaultAcsClient client = new DefaultAcsClient(profile);
        }
    }
}

Configure OpenAPI information and request parameters

Use CommonRequest to configure the common request parameters and API-specific request parameters that are required by the OpenAPI. For more information about common request parameters and their usage, see Advanced settings.

API request parameter description

To learn how to pass request parameters, view the OpenAPI metadata for the corresponding API operation. For example, the information for the RegionId request parameter of the DescribeInstanceStatus operation in the metadata is {"name":"RegionId","in":"query",...}}. In this case, "in":"query" indicates that RegionId is passed using AddQueryParameters.

Description

How to pass the parameter

When the request parameter is displayed as "in":"query".

AddQueryParameters(string key,string value)

Note

If the request parameter is a collection, pass the parameters in the format of AddQueryParameters("key.1","value1"), AddQueryParameters("key.2","value2"), and so on.

When the request parameter is displayed as "in":"body" or "in": "formData".

AddBodyParameters(string key,string value)

Note

If the request parameter is not a string, convert the parameter value to a JSON string and assign it to the `value` variable.

When you upload a file.

SetContent(byte[] content,string charset,FormatType formatType)

Note

Set the `formatType` parameter to `FormatType.RAW`.

       // 2. Create an API request and set the parameters.
        CommonRequest request = new CommonRequest();
        // 2.1  Set the common request parameters.
        request.Domain = "ecs-cn-hangzhou.aliyuncs.com"; // The endpoint supported by the cloud product.
        request.Version = "2014-05-26"; // The API version of the cloud product.
        request.Action = "DescribeInstanceStatus"; // The name of the API operation. This parameter is required for RPC API operations but not for ROA API operations.
        request.Method = MethodType.POST; // The request method. Valid values: MethodType.POST, MethodType.GET, MethodType.PUT, MethodType.DELETE, MethodType.HEAD, and MethodType.OPTIONS.
        request.Protocol = ProtocolType.HTTPS; // The request protocol. Valid values: ProtocolType.HTTPS and ProtocolType.HTTP.
        request.TimeoutInMilliSeconds = 1000; // The timeout period.
        // request.UriPattern = "/";  // The resource path. This parameter is required for ROA API operations. Do not set this parameter for RPC API operations.

        // 2.2 Set the API-specific request parameters.
        // Scenario 1: Set query parameters using AddQueryParameters(string key, string value).
        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");

        // Scenario 2: Set body parameters using AddBodyParameters(string key, string value).
        // request.AddBodyParameters("key1", "value1");
        // request.AddBodyParameters("key2", "value2");

        // Scenario 3: Upload a file using SetContent(byte[] content, string charset, FormatType formatType). The formatType parameter must be set to FormatType.RAW.
        // byte[] content = File.ReadAllBytes(@"<FILE_PATH>");
        // request.SetContent(content, "UTF-8",FormatType.RAW); 
        

Initiate a request

Use the client created in the previous step to call the GetCommonResponse method and initiate the request.

CommonResponse response = client.GetCommonResponse(request);
System.Console.WriteLine(response.Data);

Example: Call an RPC-style API

The following code shows how to use CommonRequest to call the DescribeInstanceStatus operation of ECS:

using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
class Sample
{
    static void Main(string[] args)
    {
        // Create a client instance to initiate a request.
        IClientProfile profile = DefaultProfile.GetProfile(
            // The region ID.
            "cn-hangzhou",
            // Obtain the AccessKey ID of the RAM user from an environment variable.
            Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            // Obtain the AccessKey secret of the RAM user from an environment variable.
            Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        DefaultAcsClient client = new DefaultAcsClient(profile);
        try
        {
            // Construct a request.
            CommonRequest request = new CommonRequest();
            request.Domain = "ecs.aliyuncs.com";
            request.Version = "2014-05-26";
            // Because this is an RPC API operation, you must specify ApiName(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");
            // Initiate the request and obtain 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());
        }
    }
}

Example: Call a RESTful (ROA) style API

The following code shows how to use CommonRequest to call an API operation of Container Service to view all cluster instances:

using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
class Sample
{
    static void Main(string[] args)
    {
        // Create a client to initiate a request.
        IClientProfile profile = DefaultProfile.GetProfile(
            // The region ID.
            "<REGION-ID>",
            // Obtain the AccessKey ID of the RAM user from an environment variable.
            Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            // Obtain the AccessKey secret of the RAM user from an environment variable.
            Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        DefaultAcsClient client = new DefaultAcsClient(profile);
        try
        {
            // Construct a request.
            CommonRequest request = new CommonRequest();
            request.Domain = "cs.aliyuncs.com";
            request.Version = "2015-12-15";
            // Because this is a RESTful API operation, you must specify UriPattern.
            request.UriPattern = "/clusters";
            // Initiate the request and obtain 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());
        }
    }
}

FAQ

  1. The error message "The input parameter \"AccessKeyId\" that is mandatory for processing this request is not supplied." is returned.

    Cause: The AccessKey is not configured correctly.

    Solution:

    1. Run the following commands to check whether the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured correctly:

      Linux/macOS

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

      Windows

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

      If the correct AccessKey is returned, the configuration is successful. If the returned value is empty or incorrect, set the environment variables again. For more information, see Configure environment variables in Linux, macOS, and Windows.

    2. Check your code for errors related to the AccessKey.

      Examples of common faults:

      AccessKeyId = Environment.GetEnvironmentVariable("yourAccessKeyID"),
      AccessKeySecret = Environment.GetEnvironmentVariable("yourAccessKeySecret"),

      Correct example:

      Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
      Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  2. The error message "Unhandled exception. Aliyun.Acs.Core.Exceptions.ClientException: SDK.WebException : HttpWebRequest WebException occurred, the request url is XXX.cn-hangzhou.aliyuncs.com System.Net.WebException: An error occurred while sending the request." is returned.

    Cause: The UriPattern parameter is set in the common request parameters for an RPC API operation.

    Solution: Remove the UriPattern parameter from the common request parameters.