Search code examples
c#aws-lambda.net-6.0

.net 6.0: Invalid URI: The hostname could not be parsed


I have a .net 6 project. My application's launchSettings.json is as below:

{
  "profiles": {
    "MyProject": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:56452;http://localhost:56453"
    }
  }
}

When I run the application, I get the following error

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

I tried deleting .vs folder, opened Visual Studio in Administrator Mode, even ended up restarting machine multiple times with no benefits. One of my colleagues was able to run the same app with the same launchSettings.json. So it looks like it is something to do with my local machine. Any helps are appreciated.. 

EDIT: To give more context, this is an AWS Lambda project. The whole Program.cs excluding the dependency injection is below:

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

Solution

  • I figured it out. I had AWS_LAMBDA_FUNCTION_NAME as an environment variable in my machine. For AWS Lamdba projects, it looks like .net/lambda internally uses this environment variable.