执行dotnet new webapi时遭遇NU1301错误,求解决方法
解决NU1301:无法加载NuGet服务索引的问题
问题描述
执行dotnet new webapi(曾误输入为wepapi)时,出现如下错误:
/home/.../class8.2.csproj : error NU1301: Unable to load service index to source https://api.nuget.org/v3/index.json.
已尝试修改nuget.config的多项设置,但问题未解决。项目中的program.cs和WeatherForecast.cs均为命令生成的默认代码:
program.cs 默认代码
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
WeatherForecast.cs 默认代码
namespace class8._2; public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string? Summary { get; set; } }
解决方案
以下是针对性的排查和修复步骤:
检查网络连通性:在终端执行以下命令,确认能正常访问NuGet源:
curl https://api.nuget.org/v3/index.json如果无法访问,先解决网络问题(比如防火墙拦截、DNS解析异常、代理配置错误)。
重置NuGet配置与缓存:备份当前
nuget.config后,执行命令清除缓存并生成默认配置:dotnet nuget locals all --clear dotnet new nugetconfig避免之前的错误配置持续干扰。
手动添加NuGet源:重置后仍有问题的话,手动添加官方源:
dotnet nuget add source https://api.nuget.org/v3/index.json --name nuget.org完成后执行依赖还原:
dotnet restore验证.NET SDK兼容性:通过
dotnet --version查看当前SDK版本,若版本过旧,建议升级到与webapi模板匹配的稳定版本。代理环境适配:如果处于代理网络中,临时设置代理环境变量后再测试:
export HTTP_PROXY=http://你的代理地址:端口 export HTTPS_PROXY=http://你的代理地址:端口之后重新执行
dotnet restore。
内容的提问来源于stack exchange,提问作者Gabriel Harmel
相关产品推荐
相关产品推荐

