aws-lambda-dotnet: BadImageFormatException when using serverless.AspNetCoreWebApp template with Mock Lambda Test Tool

Description

Can’t make request to lambda using Mock Lambda Test Tool when project has reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Nuget package.

Reproduction Steps

  1. Install templates: dotnet new -i "Amazon.Lambda.Templates::*"

  2. Create new project: dotnet new serverless.AspNetCoreWebApp

  3. Add Nuget reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

  4. Edit ConfigureServices in startup to enable razor pages to be loaded:

     public void ConfigureServices(IServiceCollection services)
     {
         services.AddControllers();
         var builder = services.AddRazorPages();
         builder.AddRazorRuntimeCompilation();
     }
    
  5. Configure debug configuration for mock test tool as shown in the readme for Rider: Executable and executable path: “<Configured to home directory>\.dotnet\tools\.store\amazon.lambda.testtool-3.1\0.11.4\amazon.lambda.testtool-3.1\0.11.4\tools\netcoreapp3.1\any\Amazon.Lambda.TestTool.BlazorTester.dll”

  6. Create a controller and use attribute routing

  7. Debug application and send in request using Mock Test Tool blazor interface

Request I’m using: { "httpMethod": "GET", "path": "/api/Home" }

Without Nuget reference: image

With Nuget reference: image

Logs

Environment

  • Build Version: Amazon.Lambda.AspNetCoreServer 7.0.1
  • OS Info: Windows 10
  • Build Environment: Jetbrains Rider
  • Targeted .NET Platform: netcoreapp3.1

Resolution

  • Remove reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation (no use for local debugging)

A similar issue also happens when I reference Microsoft.AspNetCore.Mvc.WebApiCompatShim too, but the error is that it can’t find System.Json.


This is a 🐛 bug-report

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 19 (18 by maintainers)

Most upvoted comments

Sorry to be a pain, I hope this comes across the right way - but surely the point in the test tool is be able to run any endpoint and to see the response as if it were running in the AWS lambda environment?

If I return a random string from it, or HTML, the string shouldn’t matter, right? When you return an MVC response from a lambda, you’d still want to see the response that the lambda will return. Whether that be headers, a HTML string or base64 etc etc. If it would work in lambda, then it should work in the test tool right?

As mentioned I will take your advice and raise another ticket if you don’t think it’s covered within this one.

@coultonluke I understand the concern, but the error is thrown by ASP.NET runtime unable to find assemblies and the possible reason might be the design of Lambda Test Tool where it loads project assemblies at runtime. There is some work being done to make test tool better, hence it would be better to open a new feature request to get it reviewed by the team. We would look forward for the feature request.

Thanks, Ashish

@coultonluke Thanks for your response. As mentioned earlier in https://github.com/aws/aws-lambda-dotnet/issues/1075#issuecomment-1031875085, the Lambda Test Tool is suitable for testing simple Lambda functions and API requests. From your error stack trace, looks like ASP.NET Razor engine is unable to find the assembly, perhaps because the current directory is the Lambda tools installation directory. We could try setting the current directory to project directory, but unsure if it would work due to the limitation mentioned in https://github.com/aws/aws-lambda-dotnet/issues/1482#issuecomment-2369635141, where we cannot create more than one AppDomain in .NET Core and later.

I would advise you to open a new feature request mentioning all the details which could be reviewed with the team.

Thanks, Ashish

@coultonluke Good morning. I was reviewing old open issues and came across this one. The issue doesn’t appear to be reproducible using latest .NET 8 AWS serverless template. Below is the code. .csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <AWSProjectType>Lambda</AWSProjectType>
    <!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
    <!-- Generate ready to run images during publishing to improve cold start time. -->
    <PublishReadyToRun>true</PublishReadyToRun>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="9.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="8.0.10" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="wwwroot\images\" />
  </ItemGroup>
</Project>

Startup.cs

namespace AWSServerlessNet8;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMvc(o => o.EnableEndpointRouting = false);
        var builder = services.AddRazorPages();
        builder.AddRazorRuntimeCompilation();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();
        app.UseMvc();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

Controllers\HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace AWSServerlessNet8.Controllers
{
    [Route("[controller]")]
    public class HomeController : Controller
    {
        [HttpGet]
        public string Index()
        {
            return "Hello";
        }
    }
}

Debugging using latest version 0.15.2 of Mock Lambda test tool and input { "httpMethod": "GET", "path": "/Home" } appears to work fine: Screenshot 2024-10-29 at 11 21 33 AM

Please verify the same at your end and confirm if this issue could be closed.

Thanks, Ashish

This issues strikes us as well. We are creating a lambda function for building emails and for that, we are using Razor as a templating engine. Unfortunately, this does not work well with the test tool as we getting the same exception as described in the issue. The fix would be deeply appreciated!

Thank you for looking into this for me. I appreciate it. I’m trying to get going with the Lambda Test Tool using an existing project, so do you think I’ll just have to remove that reference and it’s functionality in order to use the tool?

@coultonluke Removing that reference resolves the issue. I would have team look at this issue to see if something could be done, before deciding to close the issue.

Hi @coultonluke,

Good morning.

I was able to reproduce the issue in Visual Studio (not Jetbrains Rider) by:

  • Creating serverless.AspNetCoreWebApp project
  • Adding reference to Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation version 3.1.22 (since this is the latest version compatible with NetCoreApp31)
  • Enabling controller endpoints (endpoints.MapControllers();)
  • Adding a minimal HomeController:
[Route("api/[controller]")]
public class HomeController : Controller
{
    [HttpGet]
    public string Index()
    {
        return "Hello";
    }
}
  • Debug using Mock Lambda Test Tool.

I manually tried adding reference to Microsoft.CSharp 4.0.0 NuGet package, however, it gave the warning NU1701 | Package 'Microsoft.CSharp 4.0.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETCoreApp,Version=v3.1'. This package may not be fully compatible with your project..

Kindly note that Mock Lambda Test Tool uses reflection to load all the dependent assemblies. I’m unsure if Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation tries to load Microsoft.CSharp 4.0.0 at runtime in a different context.

Thanks, Ashish