'WebHost' 由于其保护级别而无法访问

'WebHost' is inaccessible due to its protection level

我正在尝试遵循 Microsoft 的 Ocelot API 网关教程(https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot)。

首先我初始化了一个新的空 ASP.NET 核心网络应用程序:

dotnet new web

然后我安装了 Ocelot 依赖项 (https://www.nuget.org/packages/Ocelot/):

dotnet add package Ocelot --version 17.0.0

那我就把教程里的代码拿来了:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System.IO;

namespace MyApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            var builder = WebHost.CreateDefaultBuilder(args);

            builder.ConfigureServices(s => s.AddSingleton(builder))
                    .ConfigureAppConfiguration(
                          ic => ic.AddJsonFile(Path.Combine("configuration",
                                                            "configuration.json")))
                    .UseStartup<Startup>();
            var host = builder.Build();
            return host;
        }
    }
}

但随后它抱怨在 BuildWebHost 方法中调用的 WebHost class“由于其保护级别而无法访问”。根据 Microsoft (https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost),WebHost“提供了使用预配置默认值创建 IWebHost 和 IWebHostBuilder 实例的便捷方法。”,看起来像这样:

public static class WebHost
...

为什么在 class 实际上是 public 时抱怨 WebHost 不可访问?我在这里错过了什么?

来自 documentationWebHost 在命名空间 Microsoft.AspNetCore 中。但是在你的代码中,它没有使用这个命名空间。

在 Visual Studio 中,您可以尝试 Go to definition on WebHost 来发现类型的来源。

正如@leiflundgren 所说,由于您的代码使用了 Microsoft.AspNetCore.Hosting,因此编译器认为您要使用 Microsoft.AspNetCore.Hosting.WebHost.

https://github.com/dotnet/aspnetcore/blob/main/src/Hosting/Hosting/src/Internal/WebHost.cs

namespace Microsoft.AspNetCore.Hosting;

internal sealed partial class WebHost : IWebHost, IAsyncDisposable
{
....
}

但是这个 class 的作用域是 internal,因此它不会公开并且可以被您的代码使用。因此出现以下错误:

WebHost is inaccessible due to its protection level.