You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AWS SDK for .NET向API Gateway发起请求?

使用AWS SDK for .NET调用API Gateway GET请求的解决方案

我之前也碰到过类似的困惑,AWS SDK for .NET针对API Gateway的调用示例确实比较零散,不过其实有两种常用的方式可以实现,根据你的API认证方式来选择:

情况1:API为公开访问(无需认证)

如果你的API Gateway没有配置任何认证(比如开放给公众访问),那完全不需要用到AWS SDK的特殊客户端,直接用.NET自带的HttpClient就能发起GET请求,简单直接:

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class PublicApiGatewayClient
{
    private static readonly HttpClient _httpClient = new HttpClient();

    public async Task<string> CallPublicApiAsync(string apiFullUrl)
    {
        try
        {
            HttpResponseMessage response = await _httpClient.GetAsync(apiFullUrl);
            response.EnsureSuccessStatusCode(); // 若返回HTTP错误状态码则抛出异常
            string responseContent = await response.Content.ReadAsStringAsync();
            return responseContent;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"请求失败: {e.Message}");
            throw;
        }
    }
}

// 使用示例
// var client = new PublicApiGatewayClient();
// var apiResult = await client.CallPublicApiAsync("https://你的APIID.execute-api.你的区域.amazonaws.com/你的阶段/资源路径");

情况2:API启用了IAM认证

如果你的API Gateway配置了IAM授权(仅授权的AWS IAM用户/角色可访问),这时候需要给请求添加SigV4签名,AWS SDK for .NET提供了现成的签名工具类,不用手动实现复杂的签名逻辑:

首先,确保安装了必要的NuGet包:

Install-Package AWSSDK.Core
Install-Package AWSSDK.SecurityToken # 若需要使用临时凭证则安装

然后通过HttpRequestSigner给请求签名,示例代码如下:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.Runtime.Signing;

public class IamAuthApiGatewayClient
{
    private static readonly HttpClient _httpClient = new HttpClient();
    private readonly AWSCredentials _awsCredentials;
    private readonly string _awsRegion;

    // 自动获取默认凭证(本地开发可通过aws configure配置,AWS托管环境自动获取角色凭证)
    public IamAuthApiGatewayClient(string region)
    {
        _awsCredentials = FallbackCredentialsFactory.GetCredentials();
        _awsRegion = region;
    }

    public async Task<string> CallIamProtectedApiAsync(string apiFullUrl)
    {
        var request = new HttpRequestMessage(HttpMethod.Get, apiFullUrl);
        
        // 创建签名器,服务名称固定为"execute-api"(API Gateway的AWS服务标识)
        var signer = new HttpRequestSigner();
        var signedRequest = await signer.SignRequestAsync(
            request,
            _awsCredentials.GetCredentials(),
            new SigningConfig
            {
                Region = _awsRegion,
                ServiceName = "execute-api"
            });

        try
        {
            HttpResponseMessage response = await _httpClient.SendAsync(signedRequest);
            response.EnsureSuccessStatusCode();
            string responseContent = await response.Content.ReadAsStringAsync();
            return responseContent;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"请求失败: {e.Message}");
            throw;
        }
    }
}

// 使用示例
// var client = new IamAuthApiGatewayClient("us-east-1");
// var apiResult = await client.CallIamProtectedApiAsync("https://你的APIID.execute-api.us-east-1.amazonaws.com/你的阶段/资源路径");

关键注意事项

  • 本地开发时,确保已通过aws configure命令或环境变量配置了有效的AWS凭证;AWS托管环境(如EC2、Lambda、ECS)中,SDK会自动获取当前角色的凭证,无需手动配置。
  • 签名时的ServiceName必须填写execute-api,这是API Gateway对应的AWS服务名称,不能写错。
  • 若使用.NET Core/.NET 5+版本,建议用IHttpClientFactory管理HttpClient实例,避免出现socket资源耗尽的问题。

如果还有具体的认证方式或者报错信息,随时补充细节,我再帮你排查~

内容的提问来源于stack exchange,提问作者Zerry Hogan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:04:02