全部產品
Search
文件中心

Alibaba Cloud SDK:代理配置

更新時間:Nov 19, 2024

本文為您介紹V2.0 .NET SDK對於代理的配置方式。

V2.0 SDK代理配置方式

說明

代理配置優先順序:RuntimeOption配置->Client配置,優先順序依次降低。

  • 通過運行時參數(RuntimeOptions)配置當前請求的代理。

    using AlibabaCloud.TeaUtil.Models;
    using Tea;
    
    namespace demo
    {
        public class Sample
        {
            static void Main(string[] args)
            {
                var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    // 從環境變數中擷取AccessKey ID值。
                    AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                    // 從環境變數中擷取AccessKey Secret值。
                    AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                    Endpoint = "ecs.cn-beijing.aliyuncs.com"
                };
    
                var escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
                var describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
                // 運行時參數設定,僅對使用了該運行時參數執行個體的請求有效
                var runtimeOptions = new RuntimeOptions();
                runtimeOptions.HttpProxy = "http://127.0.0.1:9898";
                runtimeOptions.HttpsProxy = "http://user:password@127.0.0.1:8989";
                runtimeOptions.NoProxy = "127.0.0.1,localhost";
    
                var response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
                Console.WriteLine(response.Body.ToMap());
            }
        }
    }
  • 通過Config在初始化Client階段配置請求的代理。

    using AlibabaCloud.TeaUtil.Models;
    using Tea;
    
    namespace demo
    {
        public class Sample
        {
            static void Main(string[] args)
            {
                var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    // 從環境變數中擷取AccessKey ID值。
                    AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                    // 從環境變數中擷取AccessKey Secret值。
                    AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                    Endpoint = "ecs.cn-beijing.aliyuncs.com",
                    // 代理參數設定,對使用該config的client都生效
                    NoProxy = "127.0.0.1,localhost",
                    HttpProxy = "http://127.0.0.1:9898",
                    HttpsProxy = "http://user:password@127.0.0.1:8989"
                };
    
                var escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
                var describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
                var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                var response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
                Console.WriteLine(response.Body.ToMap());
            }
        }
    }