搭建Identity脚手架时遇FileLoadException错误,求解决方法
在创建Identity脚手架时,反复抛出以下异常:
Unhandled exception. System.IO.FileLoadException: Could not load file or assembly 'dotnet-aspnet-codegenerator-design, Version=7.0.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
当前项目引用的NuGet包如下:
<ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.5" /> <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="7.0.5" /> <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Utils" Version="7.0.6" /> </ItemGroup>
已尝试降级包版本匹配.NET 7、刷新/重新加载项目,但问题未解决。
1. 统一所有相关包的版本号
项目中大部分ASP.NET Core和EF Core包使用7.0.5版本,但代码生成相关包(Microsoft.VisualStudio.Web.CodeGeneration.Design、Microsoft.VisualStudio.Web.CodeGeneration.Utils)为7.0.6,版本不一致会引发依赖加载冲突。将所有包统一为7.0.5版本:
修改项目文件中的对应包引用:
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.5" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Utils" Version="7.0.5" />
修改后执行以下命令清理并恢复依赖:
dotnet clean dotnet restore
2. 匹配全局工具版本
dotnet-aspnet-codegenerator是全局工具,其版本必须与项目.NET版本、CodeGeneration包版本一致。
先查看当前全局工具版本:
dotnet tool list --global
如果版本为7.0.6,降级到7.0.5:
dotnet tool uninstall --global dotnet-aspnet-codegenerator dotnet tool install --global dotnet-aspnet-codegenerator --version 7.0.5
3. 清除本地NuGet缓存
NuGet缓存损坏可能导致包加载异常,执行以下命令清除缓存:
dotnet nuget locals all --clear
之后重新执行dotnet restore恢复依赖。
4. 检查.NET SDK版本
确保本地安装的.NET 7 SDK版本为7.0.5(与包版本匹配),查看已安装SDK:
dotnet --list-sdks
若缺少7.0.5版本,安装对应版本的SDK。
5. 手动清理构建输出目录
项目bin/obj目录可能残留旧版本文件,引发加载冲突。手动删除这两个文件夹后重新构建:
# Linux/macOS rm -rf bin obj # Windows命令行 rmdir /s /q bin rmdir /s /q obj
执行dotnet build重新构建项目。
内容的提问来源于stack exchange,提问作者Emmanuel Genga

