Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException

Abd*_*hya 22 c# entity-framework-core asp.net-core .net-6.0

我正在使用 Asp.Net Core Web Api 6

我在迁移 DbContext 和更新数据库时遇到错误

错误

[17:07:29 INF] Application Is Starting
[17:07:29 FTL] Application terimnated unexpectedly
Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
   at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Program.<Main>$(String[] args) in C:\...\Program.cs:line 44

Run Code Online (Sandbox Code Playgroud)

但不影响迁移过程和更新数据库

因此,我的问题是,

  • 如何修复它
  • 这对以后的项目有影响吗?

程序.cs

Log.Information("Application Is Starting");

    var builder = WebApplication.CreateBuilder(args);

    // Full setup of serilog. We read log settings from appsettings.json
    builder.Host.UseSerilog((context, services, configuration) => configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext());


    // Add services to the container.
    builder.Services.AddDbContext<LocalDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("localConnection"))
    );

    builder.Services.AddControllers();
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", builder =>
            builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
            );
    });
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    var app = builder.Build();

    app.UseSerilogRequestLogging(configure =>
    {
        configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
    });

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseCors("AllowAll");

    app.UseHttpsRedirection();

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
Run Code Online (Sandbox Code Playgroud)

Jas*_*Pan 17

在任何 .NET/EF Core 6.0 RC2 项目中添加与上述类似的 try/catch IHostBulder.Build(),并尝试添加迁移可以重现该问题。

我们可以通过以下方法解决该问题:

catch (Exception ex)
{
   string type = ex.GetType().Name;
   if (type.Equals("StopTheHostException", StringComparison.Ordinal))
   {
      throw;
   }

   _logger.Fatal(ex, "Unhandled exception");
   return 1;
}
Run Code Online (Sandbox Code Playgroud)

有关此问题的更多详细信息,您可以参考这篇文章。

StopTheHostException 应该公开以便优雅地处理 #60600

  • 请注意,该异常计划在 .NET 7 中更改为“HostAbortedException”:https://github.com/dotnet/runtime/issues/60600#issuecomment-1068323222 (6认同)

Saj*_*hiy 5

更新了 NET7 及以上版本的答案:

\n
try\n{\n    var builder = WebApplication.CreateBuilder(args);\n    \xe2\x80\xa6\n    builder.Build();\n    \xe2\x80\xa6\n    Log.Information("Starting host...");\n    app.Run();\n}\ncatch (Exception ex) when (ex is not HostAbortedException)\n{\n    Log.Fatal(ex, "Host terminated unexpectedly.");\n}\nfinally\n{\n    Log.CloseAndFlush();\n}\n
Run Code Online (Sandbox Code Playgroud)\n