公共语言运行时在 .NET 6 API 中检测到无效程序?

问题描述 投票:0回答:1

我正在使用 .net6、Microsoft.NET.Sdk.Web、MVC 和 Microsoft.Extensions.DependencyInjection 6.0.0。 该异常是由 Microsoft 类引起的,没有任何可调试的内容。 在 API 方面,尝试调用请求时,我的中间件类中发生错误:

public async Task Invoke(HttpContext context)
{
    try
    {
        await _next.Invoke(context);
    }
    catch (Exception ex)
    {
        await HandleExceptionAsync(context, ex);
    }
}

例外:

System.InvalidProgramException: Common Language Runtime detected an invalid program.
   at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method93(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.InvokeCore(HttpContext context)
   at API.ErrorHandler.ErrorHandlingMiddleware.Invoke(HttpContext context) in ..\API\src\API\ErrorHandler\ErrorHandlingMiddleware.cs

主要.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\$(TargetFrameworkVersion)\GatewayApi.xml</DocumentationFile>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Asp.Versioning.Http" Version="6.5.0" />
    <PackageReference Include="NodaTime" Version="3.1.9" />
  </ItemGroup>
  <ItemGroup>
    Many project references here
  </ItemGroup>
</Project>

引用它的项目:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <AssemblyName>API</AssemblyName>
    <OutputType>Exe</OutputType>
    <PackageId>API</PackageId>
    <TypeScriptToolsVersion>2.8</TypeScriptToolsVersion>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
    <!-- Set this to true if you enable server-side prerendering -->
    <BuildServerSideRenderer>false</BuildServerSideRenderer>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.NpgSql" Version="6.0.2" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
    <PackageReference Include="Dapper" Version="2.1.15" />
    <PackageReference Include="Datadog.Trace" Version="2.21.0" />
    <PackageReference Include="FluentFTP" Version="46.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.12" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.13" />
    <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="6.0.12" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.11" />
    <PackageReference Include="NSwag.AspNetCore" Version="13.18.2" />
    <PackageReference Include="NSwag.Core" Version="13.18.2" />
    <PackageReference Include="NSwag.Generation.AspNetCore" Version="13.18.2" />
    <PackageReference Include="prometheus-net.AspNetCore" Version="7.0.0" />
    <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.0" />
    <PackageReference Include="Serilog" Version="2.12.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="7.0.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="6.0.12" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.0.3" />
    <PackageReference Include="System.IO.Compression" Version="4.3.0" />
    <PackageReference Include="System.Xml.XmlSerializer" Version="4.3.0" />
    <PackageReference Include="System.Xml.XPath.XDocument" Version="4.3.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\GatewayApi.Api\GatewayApi.Api.csproj" />
  </ItemGroup>
  <ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Update="configs\appsettings.Development.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>
  <Target Name="BuildSpa" AfterTargets="Build" Condition="'$(Configuration)' == 'Release'">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build-prod" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build-prod:ssr" Condition=" '$(BuildServerSideRenderer)' == 'true' " />
    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
      <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
      <ResolvedFileToPublish Include="@(DistFiles-&gt;'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>
</Project>

有趣的是,在默认为 InvalidProgramException 之前,它将处理对此端点的 2 个请求。

我尝试在 Dockerimage 上重现问题,在本地调试,并使用工具(例如 gitlab/kubernetes)在不同的环境中构建和运行项目,看看是否可能是我本地环境的问题。

我还更新了所有 nuget,确保解决方案中的所有版本都匹配,没有任何内容被弃用或由旧框架组成。

都没有帮助我更接近解决方案。

我希望有人帮助我达到不再发生此异常的程度。

编辑:

  • 添加了引用它的项目的 .csproj 文件和 .csproj 文件
asp.net dependency-injection .net-6.0 invalidprogramexception
1个回答
0
投票

我们最近也遇到了同样的问题:(

你找到解决办法了吗?

我们的任务是删除我们添加并注入到构造函数中的依赖项。 这是一个非常奇怪的错误,我无法理解为什么它会导致问题。 该接口的实现在其构造函数中还有其他依赖项,注释其中一些也可以解决问题,而且它与特定的依赖项无关,而是与依赖项的数量有关。 例如,假设我有 3 个依赖项: Ctor(IDep1 xx, IDep2 yy, IDep3 zz)

  • 如果我只评论 IDep1 => 它有效
  • 如果我只评论 IDep2 => 它有效
  • 如果我只评论 IDep3 => 它有效

所以这在我们的某个依赖项中并不是一个特别的问题。 但是保留所有 3 个会导致我们调用 Web 服务的第 3 次发生相同的错误。 (第一次工作正常,第二次有点慢,但工作正常,第三次调用最终在 Microsoft.Extensions.DependencyInjection 中显示“公共语言运行时检测到无效程序。”)

我们使用最新的 .NET 6 库。

我们很快就会迁移到.NET 8(一个月左右),届时我将重新添加我们的依赖项,并检查是否仍然出现相同的错误。 我会回来告诉你。

© www.soinside.com 2019 - 2024. All rights reserved.