Autofac 异常 - 安全关键与 2 级安全透明度

Autofac exception - security critical vs level 2 security transparency

我正在更新一个旧项目以使用 .net 471 而不是 462 和所有 nuget 包的最新版本。

我有很多版本控制问题需要解决,但我终于得到了一个可以构建的项目。

但是,当我执行程序时,我得到了这个异常:

System.TypeAccessException: 'Attempt by security transparent method 'Autofac.Integration.WebApi.RegistrationExtensions.RegisterApiControllers(Autofac.ContainerBuilder, System.Reflection.Assembly[])' to access security critical type 'Autofac.Builder.IRegistrationBuilder`3' failed.

其次是

Assembly 'Autofac.Integration.WebApi, Version=3.0.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.'

调用时会发生这种情况:

builder.RegisterApiControllers(ThisAssembly);

其中生成器是 Autofac ContainerBuilder

问题

像题主说的,肯定是SecurityCriticalAllowPartiallyTrustedCallersAttribute之间有什么冲突,但是我不知道我是怎么介绍的,什么是最好的做法,所以

What's going on and how can I fix this?

更新

根据 JLe 的建议,我删除了 webapi 引用并改用 webapi2。我在我的日志设置中遇到了一个相关的错误,但因为那不是 "core functionality" 我现在跳过它(我需要回到那个)看看我会得到什么。我进入浏览器屏幕,它给了我这个:

Method 'my.namespace.MyController+d__6.MoveNext()' is security transparent, but is a member of a security critical type.

我尝试将 [SecurityCritical] 放在控制器 class 上,但显然您不允许在具有该属性的 class 中进行异步调用:

Error CS4031 Async methods are not allowed in an Interface, Class, or Structure which has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.

但我无法修复,因为我正在对后端 (NServicebus ESB) 进行异步调用。

确保您使用的是 nuget.org/packages/Autofac.WebApi2 作为 WebApi2 的那个,而不是旧的 Autofac.WebApi(尽管名称空间相同,Autofac.Integration.WebApi).