常见.NET Core报错及解决方法
System.IO.FileNotFoundException: 找不到文件或程序集
确保项目中引用了正确的NuGet包。检查项目的dependencies节点或.csproj文件中的包引用是否完整。运行dotnet restore命令重新恢复依赖项。
InvalidOperationException: 无法配置服务
检查Startup.cs中的ConfigureServices方法。确认服务注册顺序正确,避免循环依赖。使用AddScoped、AddTransient或AddSingleton时需明确生命周期。
Microsoft.EntityFrameworkCore.DbUpdateException
数据库操作失败时常见该错误。检查实体模型与数据库结构的匹配性,启用日志记录查看生成的SQL语句:
optionsBuilder.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()));
HTTP 500.30 - ANCM In-Process Start Failure
应用程序启动过程中崩溃。检查Program.cs中的CreateHostBuilder配置,确保环境变量正确。查看Windows事件查看器或Azure应用服务日志获取详细错误信息。
调试与日志配置
启用详细日志
在appsettings.Development.json中配置日志级别:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
使用开发者异常页面
在Startup.Configure中添加开发环境专用的错误处理:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
依赖注入问题解决
循环依赖检测
当出现CircularDependencyException时,重构服务设计。考虑引入中介者模式或合并相关服务。使用IServiceProvider的GetRequiredService方法延迟解析依赖。
作用域服务注入单例问题
避免在单例服务中注入作用域服务。如需访问作用域服务,通过IServiceScopeFactory创建临时作用域:
public class SingletonService
{
private readonly IServiceScopeFactory _scopeFactory;
public SingletonService(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void Method()
{
using var scope = _scopeFactory.CreateScope();
var scopedService = scope.ServiceProvider.GetRequiredService<ScopedService>();
}
}
数据库迁移问题
迁移应用失败
确保连接字符串正确,并有足够的数据库权限。使用dotnet ef database update命令时指定具体迁移版本:
dotnet ef database update TargetMigration
模型快照冲突
当多人协作时出现迁移冲突,可删除Migrations文件夹并重新生成:
dotnet ef migrations add InitialCreate --context YourDbContext
部署相关问题
缺少运行时组件
部署时确保目标机器安装对应.NET Core运行时或SDK。使用独立部署模式可打包所有依赖:
dotnet publish -c Release -r win-x64 --self-contained true
文件权限问题
Linux部署时注意文件权限。确保应用有权限访问日志目录、数据库文件等关键路径。使用chmod设置适当权限:
chmod 755 /var/www/yourapp
1313

被折叠的 条评论
为什么被折叠?



