AWS Lambda部署API时IWebHostBuilder.Build()调用报错求助
解决AWS Lambda部署中IWebHostBuilder.Build()的NotSupportedException错误
错误原因
AWS Lambda的APIGatewayProxyFunction提供的IWebHostBuilder实现不允许手动调用Build()方法,该方法会由Lambda运行时内部自动执行,手动调用会触发System.NotSupportedException异常。
修正方案
方案1:通过Startup类配置服务定位器
移除Init方法中手动调用Build()的代码,仅保留builder的配置逻辑,然后在Startup类中设置服务定位器:
修改后的LambdaEntryPoint代码:
using Amazon.Lambda.AspNetCoreServer; using API_StoreSysBackendAdministrative.Extensions; namespace API_StoreSysBackendAdministrative; public class LambdaEntryPoint : APIGatewayProxyFunction { protected override void Init(IWebHostBuilder builder) { builder .UseContentRoot(Directory.GetCurrentDirectory()) .UseLambdaServer() .UseStartup<Startup>(); } }
然后在Startup.cs的Configure方法中获取服务实例:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 保留原有中间件配置逻辑 // ... // 设置服务定位器 ServiceLocator.Provider = app.ApplicationServices; }
如果需要更早获取服务,也可以在ConfigureServices中处理:
public IServiceProvider ConfigureServices(IServiceCollection services) { // 注册所有依赖服务 // ... var serviceProvider = services.BuildServiceProvider(); ServiceLocator.Provider = serviceProvider; return serviceProvider; }
方案2:使用PostBuildHook(适用于新版Amazon.Lambda.AspNetCoreServer)
如果使用的是较新版本的Amazon.Lambda.AspNetCoreServer库,可以利用PostBuildHook在框架完成构建后获取服务:
using Amazon.Lambda.AspNetCoreServer; using API_StoreSysBackendAdministrative.Extensions; namespace API_StoreSysBackendAdministrative; public class LambdaEntryPoint : APIGatewayProxyFunction { protected override void Init(IWebHostBuilder builder) { builder .UseContentRoot(Directory.GetCurrentDirectory()) .UseLambdaServer() .UseStartup<Startup>() .PostBuildHook(app => { ServiceLocator.Provider = app.Services; }); } }
内容的提问来源于stack exchange,提问作者Alejo Moya
相关产品推荐
相关产品推荐

