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

VS2022 .NET6 Web API添加控制器失败:包还原错误

.NET 6 Web API添加控制器时出现"Package restore failed"错误的解决方案

我维护一个托管在Azure的Visual Studio 2022 ASP.NET Core Web API旧项目,基于.NET 6框架,采用数据库优先模式。安装指定版本的NuGet包(Microsoft.EntityFrameworkCore [6.0.21]、Microsoft.EntityFrameworkCore.SqlServer [6.0.21]、Microsoft.EntityFrameworkCore.Design [6.0.21]、Microsoft.EntityFrameworkCore.Tools [6.0.21])并完成数据库Scaffolding生成模型和DbContext后,添加控制器时弹出错误:

运行所选代码生成器时出错:'Package restore failed. Rolling back package changes for 'project'.'

已尝试将VS从Community 17.10.5降级到Professional 17.3.7、SQL Server从2022降级到2019并更换ODBC Driver 17、安装.NET 6 SDK 6.0.424、调整NuGet包版本等操作,但均未解决问题。

以下是针对性的解决方案:

1. 清理NuGet缓存并重新还原

  • 打开Visual Studio的工具 > NuGet包管理器 > 包管理器设置,进入NuGet包管理器 > 常规,点击清除所有NuGet缓存
  • 右键项目选择还原NuGet包,等待完成后再尝试添加控制器
  • 也可使用CLI命令清理:
    dotnet nuget locals all --clear
    dotnet restore
    

2. 手动安装控制器代码生成器依赖包

代码生成器需要额外包支持,手动安装对应.NET 6版本的Microsoft.VisualStudio.Web.CodeGeneration.Design:

  • 打开包管理器控制台执行:
    Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 6.0.16
    
  • 确保该包版本与EF Core包同属.NET 6大版本即可,无需完全一致

3. 检查项目文件(.csproj)的依赖配置

打开项目的.csproj文件,确认所有依赖配置无冲突:

  • 确保所有Microsoft.EntityFrameworkCore相关包的Version统一为6.0.21
  • 移除重复的包引用,避免间接依赖版本不一致
  • 示例正确配置片段:
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.21" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.21" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.21">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.21">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.16" />
    

4. 使用.NET CLI命令生成控制器

跳过Visual Studio图形界面,直接用CLI生成控制器:

  • 打开命令行进入项目根目录,执行:
    dotnet aspnet-codegenerator controller -name [你的控制器名称] -async -api -m [实体模型类名] -dc [DbContext类名] -outDir Controllers
    
  • 替换占位符为实际项目内容,例如:
    dotnet aspnet-codegenerator controller -name ProductController -async -api -m Product -dc AppDbContext -outDir Controllers
    

5. 修复Visual Studio安装

  • 打开Visual Studio安装程序,选择已安装的17.3.7版本,点击修改
  • 确保勾选ASP.NET和Web开发工作负载下的所有必要组件,尤其是代码生成器工具相关项
  • 完成修复后重启Visual Studio再尝试操作

6. 检查Azure托管项目的本地配置

如果项目绑定Azure服务,排查本地配置问题:

  • 确认本地数据库连接字符串与Azure实例匹配,或切换到本地SQL Server测试
  • 排除因Azure服务权限、网络问题导致的包还原异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 07:16:07