文档

C# 请求构造示例

更新时间:

配置环境变量

配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET

重要
  • 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维,具体操作,请参见创建RAM用户

  • 创建AccessKey ID和AccessKey Secret,请参考创建AccessKey

  • 如果您使用的是RAM用户的AccessKey,请确保主账号已授权AliyunServiceRoleForOpenSearch服务关联角色,请参考OpenSearch-行业算法版服务关联角色,相关文档参考访问鉴权规则

  • 请不要将AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。

  • LinuxmacOS系统配置方法:

    执行以下命令,其中, <access_key_id>需替换为您RAM用户的AccessKey ID,<access_key_secret>替换为您RAM用户的AccessKey Secret。

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Windows系统配置方法

    1. 新建环境变量文件,添加环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET,并写入已准备好的AccessKey ID和AccessKey Secret。

    2. 重启Windows系统生效。

安装Package 依赖

Package 依赖地址:https://www.nuget.org/packages

dotnet add package AlibabaCloud.TeaUtil --version  0.1.5
dotnet add package AlibabaCloud.OpenSearchUtil --version 1.0.2
dotnet add package Aliyun.Credentials --version  1.2.1
dotnet add package Tea --version 0.4.0

注意

在下载依赖时,一定要严格按照对应的version下载,如有以下类似报错,请按照文档里提供的依赖的版本重新下载。

System.MissingMethodException: Method not found: 'System.String Tea.Utils.Extensions.Get(System.Collections.Generic.Dictionary`2<System.String,System.String>, System.String, System.String)'.
   at AlibabaCloud.OpenSearchUtil.Common.GetSignature(TeaRequest request, String accessKeySecret)
   at AlibabaCloud.OpenSearchUtil.Common.GetSignature(TeaRequest request, String accessKeyId, String accessKeySecret)
   at Client._request(String method, String pathname, Dictionary`2 query, Dictionary`2 headers, Object body, RuntimeOptions runtime) in D:\workspace\C#_workspace\MyDoNet\Client.cs:line 131
   at MyDoNet.Program.searchDoc(Client opensearchClient, String appName, Dictionary`2 queryParams, Dictionary`2 header, RuntimeOptions runTime) in D:\workspace\C#_workspace\MyDoNet\Program.cs:line 17
   at MyDoNet.Program.Main(String[] args) in D:\workspace\C#_workspace\MyDoNet\Program.cs:line 84

示例代码

以下是请求构造示例代码:

// This file is auto-generated, don't edit it. Thanks.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;


public class Client
{
  protected string _endpoint;
  protected string _protocol;
  protected string _userAgent;
  protected Aliyun.Credentials.Client _credential;

  public Client(Config config)
  {
    if (AlibabaCloud.TeaUtil.Common.IsUnset(config.ToMap()))
    {
      throw new TeaException(new Dictionary<string, string>
      {
        {"name", "ParameterMissing"},
        {"message", "'config' can not be unset"},
      });
    }

    if (AlibabaCloud.TeaUtil.Common.Empty(config.Type))
    {
      config.Type = "access_key";
    }

    Aliyun.Credentials.Models.Config credentialConfig = new Aliyun.Credentials.Models.Config
    {
      AccessKeyId = config.AccessKeyId,
      Type = config.Type,
      AccessKeySecret = config.AccessKeySecret,
      SecurityToken = config.SecurityToken,
    };
    this._credential = new Aliyun.Credentials.Client(credentialConfig);
    this._endpoint = config.Endpoint;
    this._protocol = config.Protocol;
    this._userAgent = config.UserAgent;
  }

  public Dictionary<string, object> _request(string method, string pathname, Dictionary<string, object> query,
    Dictionary<string, string> headers, object body, AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime)
  {
    Dictionary<string, object> runtime_ = new Dictionary<string, object>
    {
      {"timeouted", "retry"},
      {"readTimeout", runtime.ReadTimeout},
      {"connectTimeout", runtime.ConnectTimeout},
      {"httpProxy", runtime.HttpProxy},
      {"httpsProxy", runtime.HttpsProxy},
      {"noProxy", runtime.NoProxy},
      {"maxIdleConns", runtime.MaxIdleConns},
      {"retry", new Dictionary<string, object>
        {
          {"retryable", runtime.Autoretry},
          {"maxAttempts", AlibabaCloud.TeaUtil.Common.DefaultNumber(runtime.MaxAttempts, 1)},
        }
      },
      {"backoff", new Dictionary<string, object>
        {
          {"policy", AlibabaCloud.TeaUtil.Common.DefaultString(runtime.BackoffPolicy, "no")},
          {"period", AlibabaCloud.TeaUtil.Common.DefaultNumber(runtime.BackoffPeriod, 1)},
        }
      },
      {"ignoreSSL", runtime.IgnoreSSL},
    };

    TeaRequest _lastRequest = null;
    Exception _lastException = null;
    long _now = System.DateTime.Now.Millisecond;
    int _retryTimes = 0;
    while (TeaCore.AllowRetry((IDictionary) runtime_["retry"], _retryTimes, _now))
    {
      if (_retryTimes > 0)
      {
        int backoffTime = TeaCore.GetBackoffTime((IDictionary) runtime_["backoff"], _retryTimes);
        if (backoffTime > 0)
        {
          TeaCore.Sleep(backoffTime);
        }
      }

      _retryTimes = _retryTimes + 1;
      try

      {
        TeaRequest request_ = new TeaRequest();
        // 用户识别信息
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret,
        // 运行代码示例前必须先配置环境变量,参考文档上面“配置环境变量”步骤
        string accesskeyId = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
        string accessKeySecret = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        string securityToken = this._credential.GetSecurityToken();
        request_.Protocol = AlibabaCloud.TeaUtil.Common.DefaultString(_protocol, "HTTP");
        request_.Method = method;
        request_.Pathname = pathname;
        request_.Headers = TeaConverter.merge<string>
        (
          new Dictionary<string, string>()
          {
            {"user-agent",  AlibabaCloud.TeaUtil.Common.GetUserAgent(this._userAgent )},
            {"Date", AlibabaCloud.OpenSearchUtil.Common.GetDate()},
            {"host", AlibabaCloud.TeaUtil.Common.DefaultString(_endpoint, "opensearch-cn-hangzhou.aliyuncs.com")},
            {"X-Opensearch-Nonce", AlibabaCloud.TeaUtil.Common.GetNonce()},
          },
          headers
        );
        if (!AlibabaCloud.TeaUtil.Common.IsUnset(query))
        {
          request_.Query = AlibabaCloud.TeaUtil.Common.StringifyMapValue(query);
        }

        if (!AlibabaCloud.TeaUtil.Common.IsUnset(body))
        {
          string reqBody = AlibabaCloud.TeaUtil.Common.ToJSONString(body);
          request_.Headers["Content-MD5"] = AlibabaCloud.OpenSearchUtil.Common.GetContentMD5(reqBody);
          request_.Headers["Content-Type"] = "application/json";
          request_.Body = TeaCore.BytesReadable(reqBody);
        }

        if (!AlibabaCloud.TeaUtil.Common.IsUnset(securityToken))
        {
          request_.Headers["X-Opensearch-Security-Token"] = securityToken;
        }

        request_.Headers["Authorization"] =
          AlibabaCloud.OpenSearchUtil.Common.GetSignature(request_, accesskeyId, accessKeySecret);
        _lastRequest = request_;
        TeaResponse response_ = TeaCore.DoAction(request_, runtime_);

        string objStr = AlibabaCloud.TeaUtil.Common.ReadAsString(response_.Body);
        object obj = AlibabaCloud.TeaUtil.Common.ParseJSON(objStr);
        Console.WriteLine(objStr);
        Dictionary<string, object> res = AlibabaCloud.TeaUtil.Common.AssertAsMap(obj);

        if (AlibabaCloud.TeaUtil.Common.Is4xx(response_.StatusCode) ||
            AlibabaCloud.TeaUtil.Common.Is5xx(response_.StatusCode))
        {
          throw new TeaException(new Dictionary<string, object>
          {
            {"message", response_.StatusMessage},
            {"data", res},
            {"code", response_.StatusCode},
          });
        }

        return new Dictionary<string, object>
        {
          {"body", res},
          {"headers", response_.Headers}
        };
      }
      catch (Exception e)
      {
        if (TeaCore.IsRetryable(e))
        {
          _lastException = e;
          continue;
        }
        throw;
      }
    }
    throw new TeaUnretryableException(_lastRequest, _lastException);
  }
}