ASP.NET Core 3.1 不支持构建 IWebHostBuilder 的实现

Building this implementation of IWebHostBuilder is not supported in ASP.NET Core 3.1

我正在尝试将我的 .net core 2.2 升级到 3.1 并收到以下错误。

Building this implementation of IWebHostBuilder is not supported.

EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request execution pipeline before EndpointMiddleware. Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting' inside the call to 'Configure(...)' in the application startup code.

我不确定为什么会抱怨 IWebHostBuilder

有人可以指导我吗。

Program.cs

        public static void Main(string[] args)
                {
                     IHost webHost = (IHost)BuildWebHost(args);
                      var runTask = webHost.RunAsync();
                            runTask.Wait();
                            return;          
                }
         
                     
public static IHostBuilder BuildWebHost(string[] args) =>
                        Host.CreateDefaultBuilder(args)
                        .ConfigureWebHostDefaults
                        (Web =>
                        {
                            Web.UseStartup<Startup>()
                              .UseConfiguration(Configuration)
                              .UseSerilog()
                              .Build();
                        });

Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");               
                app.UseHsts();
            }
            
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseHttpContext();
          
            app.UseEndpoints(endpoints =>
                        endpoints.MapControllers());           
        }

这个

//...

   (Web =>
    {
        Web.UseStartup<Startup>()
          .UseConfiguration(Configuration)
          .UseSerilog()
          .Build(); //<--DON'T DO THIS
    });

导致原来的问题是因为

//...GenericWebHostBuilder

public IWebHost Build()
{
    throw new NotSupportedException($"Building this implementation of {nameof(IWebHostBuilder)} is not supported.");
}

Source

代码需要重构为

public static async Task Main(string[] args) {
     IHost host = BuildWebHost(args);
     await host.RunAsync();  
}
                 
public static IHost BuildWebHost(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(Web => {
            Web.UseStartup<Startup>()
              .UseConfiguration(Configuration)
              .UseSerilog();
        })
        .Build();

为了遵循文档中建议的格式。

如果代码不需要异步,那么这也可以工作

public static void Main(string[] args) {
    IHost host = BuildWebHost(args);
    host.Run();  
}