ASP.NET Core 6中CreateHostBuilder不存在于当前上下文的问题
.NET 6中"The name CreateHostBuilder does not exist in the current context"错误解决方法
问题场景
跟着.NET 5教程学习,使用VS2022搭配.NET 6时出现错误:The name CreateHostBuilder does not exist in the current context。推测这与.NET 6将Startup.cs整合到Program.cs的变化有关,于是把代码都放到Program.cs中,但错误出在以下代码行:
var host = CreateHostBuilder(args).Build();
错误原因
.NET 6采用了顶级语句的简化项目模板,不再使用旧版的CreateHostBuilder方法,而是通过WebApplication.CreateBuilder(args)创建的builder对象完成服务注册和应用构建。原有代码同时混用了旧版主机构建逻辑和新版WebApplication模板,不仅导致CreateHostBuilder未定义的错误,还会造成后续中间件配置失效。
修正后的代码
以下是调整后的完整Program.cs代码,适配.NET 6的模板结构:
using DevBlogMVC.Data; using DevBlogMVC.Models; using DevBlogMVC.Services; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // PostgreSQL连接配置 var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString)); // 统一配置Identity服务,避免重复注册 builder.Services.AddIdentity<BlogUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true) .AddDefaultUI() .AddDefaultTokenProviders() .AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); // 注册数据初始化服务 builder.Services.AddScoped<DataService>(); builder.Services.AddControllersWithViews(); var app = builder.Build(); // 在应用启动前执行数据初始化操作 using (var scope = app.Services.CreateScope()) { var dataService = scope.ServiceProvider.GetRequiredService<DataService>(); await dataService.ManageDataAsync(); } // 配置HTTP请求管道 if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); app.Run();
关键修改说明
- 移除无效的
CreateHostBuilder(args).Build()和host.Run()代码,改用.NET 6标准的builder.Build()创建应用实例 - 将数据初始化逻辑移至应用构建完成后、启动前,通过
app.Services.CreateScope()获取服务作用域,这是.NET 6中获取依赖注入服务的推荐方式 - 合并重复的
AddIdentityCore和AddIdentity配置,避免服务注册冲突 - 确保所有中间件配置都在
app实例创建后执行,符合.NET 6的模板执行顺序
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

