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

部署ASP.NET Core 8 Web API至AWS Lambda时触发异常求助

解决ASP.NET Core 8 Web API部署AWS Lambda/API Gateway的错误问题

核心错误原因

第一个TargetInvocationException的根源是:.NET 8采用顶级语句编写的Program.cs编译后生成的类没有Configure或ConfigureProduction方法,而你在LambdaEntryPoint中使用UseStartup<Program>(),ASP.NET的启动加载器会尝试寻找这些方法,导致匹配失败。

第二个NullReferenceException是因为自定义Startup类未正确适配Lambda的请求处理模型,配置逻辑不完整导致空引用。


解决方案

1. 修正LambdaEntryPoint.cs

移除错误的UseStartup<Program>()调用,直接在Init方法中复用Program.cs的服务和中间件配置逻辑:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{  
    protected override void Init(IWebHostBuilder builder)
    {
        builder
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseLambdaServer()
            .ConfigureServices(services =>
            {
                // 复制Program.cs中的服务配置
                services.AddControllers();
                services.AddCors(options =>
                {
                    options.AddPolicy("AllowSpecificOrigin",
                        policy => policy.WithOrigins("你的允许源地址")
                                        .AllowAnyHeader()
                                        .AllowAnyMethod());
                });
                services.AddAWSLambdaHosting(LambdaEventSource.RestApi);
            })
            .Configure((context, app) =>
            {
                // 复制Program.cs中的中间件配置
                if (app.Environment.IsDevelopment())
                {
                    app.UseSwagger();
                    app.UseSwaggerUI();
                }

                app.UseCors("AllowSpecificOrigin");
                app.UseHttpsRedirection();
                app.UseRouting();
                app.UseAuthorization();
                app.MapControllers();
            });
    }        
}

2. 优化Program.cs(可选但推荐)

为避免代码重复,将Program.cs的配置逻辑提取为静态方法,方便LambdaEntryPoint调用:

// 显式声明Program类,便于LambdaEntryPoint访问
public partial class Program
{
    public static void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                policy => policy.WithOrigins("你的允许源地址")
                                .AllowAnyHeader()
                                .AllowAnyMethod());
        });
        services.AddAWSLambdaHosting(LambdaEventSource.RestApi);
    }

    public static void ConfigurePipeline(WebApplication app)
    {
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseCors("AllowSpecificOrigin");
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
        app.MapControllers();
    }

    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        ConfigureServices(builder.Services);

        var app = builder.Build();
        ConfigurePipeline(app);

        app.Run();
    }
}

修改后的LambdaEntryPoint可简化为:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{  
    protected override void Init(IWebHostBuilder builder)
    {
        builder
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseLambdaServer()
            .ConfigureServices(Program.ConfigureServices)
            .Configure((context, app) => Program.ConfigurePipeline(app));
    }        
}

3. 调整项目编译配置

在项目文件(.csproj)中添加以下配置,确保生成适配AWS Lambda的部署包:

<PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <AWSProjectType>Lambda</AWSProjectType>
    <RuntimeIdentifier>linux-x64</RuntimeIdentifier>
    <PublishReadyToRun>true</PublishReadyToRun>
    <PublishSingleFile>true</PublishSingleFile>
    <SelfContained>true</SelfContained>
</PropertyGroup>

4. 重新部署验证

  • 使用serverless.template重新打包部署到AWS,确保部署包包含所有依赖
  • 在AWS控制台测试Lambda函数,或通过API Gateway发送请求验证响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:09:50