.NET 6 AWS Lambda项目启动报错:Invalid URI: 无法解析主机名
.NET 6 AWS Lambda本地运行报错:Invalid URI: The hostname could not be parsed.
问题详情
我有一个.NET 6的AWS Lambda项目,launchSettings.json配置如下:
{ "profiles": { "MyProject": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "https://localhost:56452;http://localhost:56453" } } }
运行应用时抛出以下错误:
Invalid URI: The hostname could not be parsed. at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind, UriCreationOptions& creationOptions) at System.Uri..ctor(String uriString, UriKind uriKind) at Amazon.Lambda.RuntimeSupport.InternalRuntimeApiClient.<NextAsync>d__13.MoveNext() at Amazon.Lambda.RuntimeSupport.RuntimeApiClient.<GetNextInvocationAsync>d__16.MoveNext() at Amazon.Lambda.RuntimeSupport.LambdaBootstrap.<InvokeOnceAsync>d__17.MoveNext() at Amazon.Lambda.RuntimeSupport.LambdaBootstrap.<RunAsync>d__15.MoveNext() at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__37.MoveNext() at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__12.MoveNext() at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext() at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext() at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host) at Microsoft.AspNetCore.Builder.WebApplication.Run(String url) at Program.<Main>$(String[] args) in <My Solution Path>\Program.cs:line 94
已尝试删除.vs文件夹、管理员模式启动Visual Studio、重启机器,均未解决问题。同事使用相同配置可正常运行,推测问题出在本地环境。
补充:项目Program.cs代码(移除依赖注入部分):
using Amazon.XRay.Recorder.Handlers.AwsSdk; using Asp.Versioning; //using for DI //using for DI using Moschen.AwsLambdaAuthenticationHandler; using Moschen.AwsLambdaAuthenticationHandler.Jwt; using System.Text.Json; using System.Text.Json.Serialization; var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (!string.IsNullOrWhiteSpace(environment) && environment != "Local") { AWSSDKHandler.RegisterXRayForAllServices(); } var builder = WebApplication.CreateBuilder(args); // Set request timeout builder.WebHost.UseKestrel(options => { options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(5); options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(5); }); //Logger builder.Logging .ClearProviders() .AddJsonConsole() .AddLambdaLogger(new LambdaLoggerOptions { IncludeCategory = true, IncludeLogLevel = true, IncludeNewline = true, IncludeEventId = true, IncludeException = true }); builder.Services.AddTransient(s => s.GetRequiredService<ILoggerFactory>().CreateLogger("default")); builder.Services.AddHttpContextAccessor(); // Add services to the container. builder.Services .AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); }); builder.Services .AddAuthentication(AwsAuthorizerDefaults.AuthenticationScheme) .AddAwsAuthorizer(); builder.Services .AddAuthentication(AwsJwtAuthorizerDefaults.AuthenticationScheme) .AddJwtAuthorizer(options => { options.ExtractClaimsFromToken = true; }); // Dependency Injection for the project //... //... //... builder.Services.AddApiVersioning(options => { options.ReportApiVersions = false; options.ApiVersionReader = new UrlSegmentApiVersionReader(); options.DefaultApiVersion = new ApiVersion(1); options.AssumeDefaultVersionWhenUnspecified = true; }); builder.Services .AddHealthChecks(); // Add AWS Lambda support. When running the application as an AWS Server-less application, Kestrel is replaced // with a Lambda function contained in the Amazon.Lambda.AspNetCoreServer package, which marshals the request into the ASP.NET Core hosting framework. builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); var app = builder.Build(); app.UseHttpsRedirection(); app.UseHealthChecks("/health"); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => "Welcome to running ASP.NET Core Minimal API on AWS Lambda"); app.Run(); //Exception is thrown from here
解决步骤
- 检查并清理冲突环境变量:查看系统环境变量中是否存在
AWS_LAMBDA_RUNTIME_API,如果有则临时删除或重命名,重启Visual Studio后重试。这个变量是Lambda运行时专用的,本地调试时被错误设置会导致URI解析失败。 - 修改launchSettings.json强制本地模式:在
environmentVariables中添加"AWS_LAMBDA_RUNTIME_API": "",明确告诉应用本地使用Kestrel而非Lambda运行时:"environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "AWS_LAMBDA_RUNTIME_API": "" } - 更新Lambda相关NuGet包:确保
Amazon.Lambda.AspNetCoreServer包版本与.NET 6兼容,建议更新到最新稳定版,旧版本可能存在本地调试的URI解析bug。 - 清理项目缓存并重新还原:删除项目根目录下的
bin和obj文件夹,执行dotnet clean和dotnet restore命令后重新生成项目。 - 验证hosts文件配置:检查本地hosts文件中是否存在
127.0.0.1 localhost的映射,若缺失则添加(需要管理员权限)。
内容的提问来源于stack exchange,提问作者user007
相关产品推荐
相关产品推荐

