'.NET Core 3.1 AWS Lambda Could not load file or assembly System.Runtime.Loader, Version=4.1.1.0

This is my aws-lambda-tools-default.json

{
  "Information": [
    "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
    "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
    "dotnet lambda help",
    "All the command line options for the Lambda command can be specified in this file."
  ],
  "profile": "PP",
  "region": "RR",
  "configuration": "Release",
  "framework": "netcoreapp3.1",
  "s3-prefix": "API/",
  "template": "serverless.template",
  "template-parameters": "",
  "msbuild-parameters": "--self-contained true"
}

When I publish this to Lambda, no errors happen. But when I run the api, I get this error on CloudWatch:

Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime.Loader, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

File name: 'System.Runtime.Loader, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

23 Aug 2021 09:10:44,882 [WARN] ([email protected]:331 errno: None) run_dotnet(dotnet_path, &args) failed

Failed to execute the Lambda function. The dotnet CLI failed to start with the provided deployment package. Please check CloudWatch logs for this Lambda function to get detailed information about this failure.: LambdaException

Does this have anything to do with me compiling it as a self contained app?

When I compile it on my local PC, it runs without any issue. This is the csproj on my local PC

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <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>
    <SatelliteResourceLanguages>en</SatelliteResourceLanguages>
    <PublishReadyToRun>true</PublishReadyToRun>
    <PublishTrimmed>true</PublishTrimmed>
    <SelfContained>true</SelfContained>
    <RuntimeIdentifier>win10-x64</RuntimeIdentifier>
    <OutputType>Exe</OutputType>
</PropertyGroup>

EDIT: I had to add the nuget packages for System.Runtime.Loader and System.IO.Pipelines.

However, I discovered that PublishTrimmed caused this error to reappear as well.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source