dotnet add
除了可以對專案增加 reference 外,也可以用來安裝 NuGet 套件。
指令差異:
dotnet add <PROJECT> reference <PROJECT_PATH>
dotnet add <PROJECT> package <PACKAGE_NAME>
# No Package
$ dotnet list package
Unable to read a package reference from the project `/Users/fntsr/Projects/dotnet-sln/WebProj/WebProj.csproj`. Please make sure that your project file and project.assets.json file are in sync by running restore.
# Add package(s)
...
# Have package(s)
$ dotnet list package
Project 'WebProj' has the following package references
[netcoreapp2.2]:
Top-level Package Requested Resolved
> Microsoft.AspNetCore.App (A) [2.2.0, ) 2.2.0
> Microsoft.AspNetCore.Razor.Design 2.2.0 2.2.0
> Microsoft.NETCore.App (A) [2.2.0, ) 2.2.0
> Newtonsoft.Json 12.0.2 12.0.2
(A) : Auto-referenced package.
# ~/dotnet-sln/WebProj
$ dotnet add package Newtonsoft.Json
Writing /var/folders/hx/lgdjx1l93pq08s35hhwb0py40000gn/T/tmpK3nJij.tmp
info : Adding PackageReference for package 'Newtonsoft.Json' into project '/Users/ironman/dotnet-sln/WebProj/WebProj.csproj'.
info : Restoring packages for /Users/ironman/dotnet-sln/WebProj/WebProj.csproj...
info : GET https://api.nuget.org/v3-flatcontainer/newtonsoft.json/index.json
info : OK https://api.nuget.org/v3-flatcontainer/newtonsoft.json/index.json 897ms
info : Package 'Newtonsoft.Json' is compatible with all the specified frameworks in project '/Users/ironman/dotnet-sln/WebProj/WebProj.csproj'.
info : PackageReference for package 'Newtonsoft.Json' version '12.0.2' added to file '/Users/ironman/dotnet-sln/WebProj/WebProj.csproj'.
info : Committing restore...
info : Writing assets file to disk. Path: /Users/ironman/dotnet-sln/WebProj/obj/project.assets.json
log : Restore completed in 6.24 sec for /Users/ironman/dotnet-sln/WebProj/WebProj.csproj.
# ~/dotnet-sln/WebProj
dotnet remove package Newtonsoft.Json
info : Removing PackageReference for package 'Newtonsoft.Json' from project '/Users/ironman/dotnet-sln/WebProj/WebProj.csproj'.
在 Solution 或是 Project 跟目錄底下新增一個 nuget.config
的檔案,並在裡面填入下面的內容。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="Foo" value="https://foo.bar/nuget" />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>
這是指我們會優先使用 https://foo.bar/nuget
作為第一個 NuGet 套件的 Source,如果找不到會再尋找 https://api.nuget.org/v3/index.json
提供的套件清單。