You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core项目启动触发System.AggregateException的解决求助

解决ASP.NET Core启动时的System.AggregateException问题

错误核心原因

从错误信息里的Unable to resolve service for type 'eProject3.Data.ApplicationDbContext'可以明确两点:

  • Identity相关服务(如UserManager、SignInManager)依赖ApplicationDbContext,但你没有将这个DbContext注册到依赖注入容器——代码里注册DbContext的代码被注释掉了。
  • 存在命名空间不匹配:代码里引用的是MB3.Data,但错误提示中DbContext属于eProject3.Data,二者需要统一。

修复步骤

  1. 恢复DbContext的注册代码
    取消Program.cs中被注释的AddDbContext代码块,同时修正命名空间:要么把using语句改为using eProject3.Data;,要么调整ApplicationDbContext所在的项目命名空间为MB3.Data,保证二者一致。

  2. 验证连接字符串配置
    检查appsettings.json里的DefaultConnection是否正确指向你的SQL Server数据库,示例配置:

    "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=eProject3;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
    
  3. 执行数据库迁移(首次搭建时)
    如果是第一次配置数据库,需要执行迁移命令初始化数据库:

    • 使用Package Manager Console:
      Add-Migration InitialCreate
      Update-Database
      
    • 使用.NET CLI终端:
      dotnet ef migrations add InitialCreate
      dotnet ef database update
      

修正后的Program.cs代码示例

using eProject3.Data; // 确保命名空间与错误提示一致
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
// 恢复DbContext注册
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
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();

内容的提问来源于stack exchange,提问作者Noo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 11:35:03