无法从 .Net 5.0 WebApi 访问 GlobalConfiguration.Configuration

Can't access GlobalConfiguration.Configuration from .Net 5.0 WebApi

GlobalConfiguration.Configuration 似乎在新的 ASP.NET Core WebApi 项目 (.Net 5.0) 中不可用。

重现步骤:

  1. 创建一个新的“ASP.NET Core Web Api”项目。 (目标框架:.NET 5.0,语言:C#)
  2. 将此行添加到代码的任意位置:var config = GlobalConfiguration.Configuration;

例如将其添加到 Startup.cs:

public Startup(IConfiguration configuration)
{
        var c = GlobalConfiguration.Configuration;    // this line was added
        Configuration = configuration;
}
  1. 您需要 System.Web.Http.GlobalConfiguration 的包裹 这似乎与 Microsoft.AspNet.WebApi.WebHost Nuget 包相对应,所以安装它:
Install-Package Microsoft.AspNet.WebApi.WebHost -Version 5.2.7
  1. 运行 应用程序,看到它在我们的新代码行失败,但出现以下异常:
System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'System.Web.Routing.RouteTable'
  from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
  Source=System.Web.Http.WebHost
  StackTrace:
   at System.Web.Http.GlobalConfiguration.<>c.<CreateConfiguration>b__11_0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.get_Value()
   at System.Web.Http.GlobalConfiguration.get_Configuration()
   at AspNetCore5._0.Program.Main(String[] args) in C:\work\AspNetCore5.0\Program.cs:line 17

我最终想要实现的目标... 是使用 AutoFac 作为我的依赖项解析器(我得到了这个工作)。但是当我遵循 AutoFac's documentation on FilterProviders to created my own custom Filters (e.g. ModelValidationFilter, ResponseFilter, ExceptionFilter), it requires that I obtain GlobalConfiguration.Configuration. AutoFac documentation on obtaining GlobalConfiguration 时,建议我为 'standard IIS hosting' 获得 GlobalConfiguration.Configuration,如下所示:

var config = GlobalConfiguration.Configuration;

...但显然失败了。

对于这方面的任何帮助或建议,我将不胜感激。 谢谢!

ASP.NET Core 与 ASP.NET 或 ASP.NET WebAPI 不同,虽然控制器等许多东西只需要对端口进行微小调整,但配置和路由却大不相同.

由于您的最终目标是将 AutoFac 安装为依赖项解析器,请尝试按照 AutoFac 的 documentation for ASP.NET Core.