.NET CLI 命令行工具
大约 13 分钟约 3884 字
.NET CLI 命令行工具
简介
.NET CLI(Command Line Interface)是 .NET SDK 提供的跨平台命令行工具,用于开发、构建、运行和发布 .NET 应用程序。它是 .NET 开发工作流的核心工具,支持项目管理、依赖管理、测试执行和部署发布等全生命周期操作。无论使用 Visual Studio、VS Code 还是其他编辑器,掌握 .NET CLI 都能显著提升开发效率和自动化能力。
特点
项目管理命令
创建项目
# 创建控制台应用
dotnet new console -n MyApp -o ./src/MyApp
# 创建类库项目
dotnet new classlib -n MyLibrary -o ./src/MyLibrary
# 创建 ASP.NET Core Web API
dotnet new webapi -n MyApi -o ./src/MyApi --no-https
# 创建 Blazor Server 应用
dotnet new blazorserver -n MyBlazorApp
# 创建 Blazor WebAssembly 应用
dotnet new blazorwasm -n MyWasmApp
# 创建 xUnit 测试项目
dotnet new xunit -n MyTests -o ./tests/MyTests
# 创建 NUnit 测试项目
dotnet new nunit -n MyNUnitTests
# 创建解决方案文件
dotnet new sln -n MySolution
# 将项目添加到解决方案
dotnet sln add ./src/MyApp/MyApp.csproj
dotnet sln add ./src/MyLibrary/MyLibrary.csproj
dotnet sln add ./tests/MyTests/MyTests.csproj
# 查看解决方案中的项目
dotnet sln list
# 移除项目
dotnet sln remove ./src/MyApp/MyApp.csproj自定义模板
# 列出已安装的模板
dotnet new list
# 搜索在线模板
dotnet new search clean-architecture
# 安装模板包
dotnet new install Ardalis.ApiEndpoints.Template
dotnet new install Clean.Architecture.Solution.Template
# 卸载模板包
dotnet new uninstall Ardalis.ApiEndpoints.Template
# 使用已安装的模板创建项目
dotnet new cleanarch -n MyCleanApp
# 创建自定义模板
# 1. 创建模板配置文件 .template.config/template.json
# 2. 打包为 NuGet
# 3. 安装后即可使用构建与运行
构建命令
# 构建项目
dotnet build
# 构建指定项目(Release 模式)
dotnet build ./src/MyApi/MyApi.csproj -c Release
# 构建时不恢复依赖
dotnet build --no-restore
# 指定目标框架构建
dotnet build -f net8.0
# 指定运行时标识符构建
dotnet build -r win-x64
# 清理构建输出
dotnet clean
# 清理并重新构建
dotnet clean && dotnet build运行命令
# 运行项目
dotnet run --project ./src/MyApp
# 运行时传递参数
dotnet run --project ./src/MyApp -- --environment Production --port 8080
# 指定配置运行
dotnet run -c Release
# 指定环境变量
dotnet run --environment Development
# 指定监听 URL
dotnet run --urls "https://localhost:5001;http://localhost:5000"
# 直接运行 DLL(无需项目文件)
dotnet ./publish/MyApi.dll
# 使用 launchSettings.json 中的配置
dotnet run --launch-profile https依赖管理
NuGet 包管理
# 添加 NuGet 包
dotnet add package Serilog
dotnet add package Serilog --version 3.1.1
# 添加到指定项目
dotnet add ./src/MyApi/MyApi.csproj package Microsoft.EntityFrameworkCore
# 添加开发依赖
dotnet add package Moq --prerelease
# 移除 NuGet 包
dotnet remove package Moq
# 列出包引用
dotnet list package
dotnet list package --outdated
dotnet list package --vulnerable
# 恢复依赖
dotnet restore
# 使用指定 NuGet 源恢复
dotnet restore -s https://api.nuget.org/v3/index.json
dotnet restore -s https://my-private-feed/v3/index.json
# 清除 NuGet 缓存
dotnet nuget locals all --clear项目引用管理
# 添加项目引用
dotnet add ./src/MyApi/MyApi.csproj reference ./src/MyLibrary/MyLibrary.csproj
# 添加多个项目引用
dotnet add ./src/MyApi/MyApi.csproj reference \
./src/MyLibrary/MyLibrary.csproj \
./src/MyCommon/MyCommon.csproj
# 移除项目引用
dotnet remove ./src/MyApi/MyApi.csproj reference ./src/MyLibrary/MyLibrary.csproj
# 列出项目引用
dotnet list ./src/MyApi/MyApi.csproj reference发布部署
发布命令
# 框架依赖部署(FDD)- 需要目标机器安装 .NET Runtime
dotnet publish -c Release -o ./publish
# 独立部署(SCD)- 包含 .NET Runtime,不需要预安装
dotnet publish -c Release -r win-x64 --self-contained -o ./publish-win
dotnet publish -c Release -r linux-x64 --self-contained -o ./publish-linux
dotnet publish -c Release -r osx-x64 --self-contained -o ./publish-mac
# 单文件发布
dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true
# 裁剪发布(减小体积)
dotnet publish -c Release -r win-x64 --self-contained -p:PublishTrimmed=true
# ReadyToRun 编译(提升启动速度)
dotnet publish -c Release -r win-x64 -p:PublishReadyToRun=true
# Native AOT 发布(.NET 8+)
dotnet publish -c Release -r win-x64 -p:PublishAot=true
# 指定版本号发布
dotnet publish -c Release -p:Version=1.2.3 -p:AssemblyVersion=1.2.3.0
# Docker 相关发布
dotnet publish -c Release -r linux-x64 --self-contained -o ./publish-docker发布配置文件(PublishProfile)
<!-- Properties/PublishProfiles/FolderProfile.pubxml -->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishDir>bin\Release\net8.0\win-x64\publish\</PublishDir>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishTrimmed>true</PublishTrimmed>
</PropertyGroup>
</Project># 使用发布配置文件
dotnet publish -p:PublishProfile=FolderProfile测试命令
运行测试
# 运行所有测试
dotnet test
# 运行指定项目的测试
dotnet test ./tests/MyTests/MyTests.csproj
# 运行并显示详细输出
dotnet test -v detailed
# 运行指定标签的测试
dotnet test --filter "Category=Integration"
dotnet test --filter "Priority=High"
# 按名称过滤
dotnet test --filter "FullyQualifiedName~UserServiceTests"
dotnet test --filter "TestMethodName~CreateOrder"
# 排除特定测试
dotnet test --filter "Category!=Integration"
# 生成代码覆盖率报告
dotnet test --collect:"XPlat Code Coverage"
# 指定覆盖率格式
dotnet test --collect:"XPlat Code Coverage;Format=cobertura"
# 并行运行测试
dotnet test --maxcpucount:4
# 不构建直接运行测试
dotnet test --no-build测试结果输出
# 输出为 TRX 格式
dotnet test --logger "trx;LogFileName=test_results.trx"
# 输出到指定目录
dotnet test --logger "trx" --results-directory ./test-results
# 多种日志格式
dotnet test --logger "console;verbosity=detailed"
dotnet test --logger "html;LogFileName=report.html"EF Core CLI 工具
# 安装 EF Core 全局工具
dotnet tool install --global dotnet-ef
# 更新到最新版本
dotnet tool update --global dotnet-ef
# 创建迁移
dotnet ef migrations add InitialCreate --project ./src/MyApi
# 更新数据库
dotnet ef database update --project ./src/MyApi
# 移除最后一次迁移
dotnet ef migrations remove --project ./src/MyApi
# 生成 SQL 脚本
dotnet ef migrations script --project ./src/MyApi --output migration.sql
# 查看迁移状态
dotnet ef migrations list --project ./src/MyApi
# 从现有数据库生成模型(反向工程)
dotnet ef dbcontext scaffold "Server=.;Database=MyDb;Trusted_Connection=True" \
Microsoft.EntityFrameworkCore.SqlServer --project ./src/MyApi全局工具管理
# 安装全局工具
dotnet tool install --global dotnet-format
dotnet tool install --global dotnet-outdated-tool
dotnet tool install --global dotnet-sonarscanner
# 安装特定版本
dotnet tool install --global dotnet-ef --version 8.0.0
# 安装本地工具(项目级别)
dotnet new tool-manifest
dotnet tool install dotnet-format
# 列出已安装的工具
dotnet tool list -g
dotnet tool list
# 更新工具
dotnet tool update -g dotnet-ef
# 卸载工具
dotnet tool uninstall -g dotnet-format
# 使用 dotnet-format 格式化代码
dotnet format
dotnet format --verify-no-changes
dotnet format ./src/MyApi/MyApi.csproj高级发布场景
Docker 集成发布
# 为 Docker 多阶段构建准备发布
# 第一步:在 SDK 镜像中发布
dotnet publish -c Release -r linux-x64 --self-contained false -o ./publish
# 使用 Chiseled 容器镜像(.NET 8 推荐方式)
# 更小的镜像体积,更少的攻击面
dotnet publish -c Release -r linux-x64 --os linux -t:PublishContainer
# 自定义容器镜像名称和标签
dotnet publish -c Release -t:PublishContainer \
-p:ContainerImageName=myapp \
-p:ContainerImageTag=v1.0.0 \
-p:ContainerBaseImage=mcr.microsoft.com/dotnet/aspnet:8.0-alpine
# 发布为 Native AOT 并打包到 Docker
dotnet publish -c Release -r linux-x64 -p:PublishAot=true \
-t:PublishContainer# 完整的 .NET 8 Dockerfile 示例
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
# 先复制 csproj 文件利用缓存
COPY ["src/MyApi/MyApi.csproj", "src/MyApi/"]
RUN dotnet restore "src/MyApi/MyApi.csproj"
# 复制源码并发布
COPY . .
RUN dotnet publish "src/MyApi/MyApi.csproj" \
-c Release -o /app/publish --no-restore
# 运行阶段使用 Chiseled 镜像
FROM mcr.microsoft.com/dotnet/aspnet:8.0-chiseled AS runtime
WORKDIR /app
COPY --from=build /app/publish .
# 非 root 用户(Chisepled 镜像默认已是 non-root)
EXPOSE 8080
ENTRYPOINT ["dotnet", "MyApi.dll"]发布优化对比
发布方式对比(以一个中等规模 Web API 为例):
| 发布方式 | 大小 | 启动时间 | 兼容性 | 适用场景 |
|---------------------------|--------|---------|-------------|-----------------|
| 框架依赖(FDD) | ~15MB | ~200ms | 需安装 Runtime | 服务器已有 Runtime |
| 独立部署(SCD) | ~80MB | ~200ms | 无需安装 | 独立服务器部署 |
| 单文件 + 裁剪 | ~30MB | ~300ms | 注意反射场景 | 小型工具/CLI |
| Native AOT | ~15MB | ~20ms | 限制较多 | 高性能/云原生 |
| PublishReadyToRun | ~40MB | ~100ms | 平台绑定 | 需快速启动 |
Native AOT 限制:
- 不支持运行时动态加载程序集
- 不支持反射创建未知类型
- 不支持 C# 的 dynamic 关键字
- 不支持 COM 互操作
- 不支持 System.Reflection.Emit
- 需要标记需保留的类型:[DynamicDependency] 或 RootedTypeNuGet 包管理进阶
NuGet 配置
# 查看 NuGet 配置
dotnet nuget locals all --list
# 配置私有 NuGet 源
dotnet nuget add source https://my-private-feed/v3/index.json \
-n MyPrivateFeed -u user -p password --store-password-in-clear-text
# nuget.config 文件(推荐方式)
# 放在项目根目录或用户目录下<!-- nuget.config -->
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<add key="my-private" value="https://my-feed/v3/index.json" />
</packageSources>
<packageSourceMapping>
<packageSource key="nuget.org">
<package pattern="*" />
</packageSource>
<packageSource key="my-private">
<package pattern="MyCompany.*" />
</packageSource>
</packageSourceMapping>
</configuration>包版本管理
# 查看过期的包
dotnet list package --outdated --include-prerelease
# 查看有安全漏洞的包
dotnet list package --vulnerable
# 指定版本范围
# 精确版本: dotnet add package Serilog --version 3.1.1
# 最低版本: dotnet add package Serilog --version 3.1.1-*
# 自动升级补丁: 在 csproj 中使用 [3.1.1, 3.2.0)
# Central Package Management(集中包管理)
# 在目录下创建 Directory.Packages.props<!-- Directory.Packages.props - 集中管理包版本 -->
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Serilog" Version="3.1.1" />
<PackageVersion Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.3" />
<PackageVersion Include="AutoMapper" Version="13.0.1" />
<PackageVersion Include="FluentValidation" Version="11.9.0" />
</ItemGroup>
</Project>
<!-- 在 csproj 中引用(不指定版本) -->
<!-- <PackageReference Include="Serilog" /> -->打包与发布 NuGet 包
# 打包为 NuGet 包
dotnet pack ./src/MyLibrary/MyLibrary.csproj -c Release
# 指定输出目录和版本号
dotnet pack -c Release -o ./artifacts -p:PackageVersion=1.2.3
# 包含源码符号包
dotnet pack -c Release --include-symbols -p:SymbolPackageFormat=snupkg
# 推送到 NuGet 源
dotnet nuget push ./artifacts/MyLibrary.1.2.3.nupkg \
-s https://api.nuget.org/v3/index.json -k YOUR_API_KEY
# 推送到私有源
dotnet nuget push ./artifacts/MyLibrary.1.2.3.nupkg \
-s https://my-private-feed/v3/index.jsonCI/CD 集成脚本
GitHub Actions
# .github/workflows/build.yml
name: Build and Test
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
dotnet-version: ['8.0.x']
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ matrix.dotnet-version }}
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore -c Release
- name: Test
run: dotnet test --no-build -c Release --collect:"XPlat Code Coverage"
- name: Publish
run: dotnet publish -c Release -o ./publish
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: publish-output
path: ./publish/常用 CLI 别名配置
# 在 .bashrc 或 .zshrc 中添加常用别名
alias db='dotnet build'
alias dr='dotnet run'
alias dt='dotnet test'
alias dp='dotnet publish -c Release'
alias dw='dotnet watch run'
alias dfa='dotnet format'
alias dtr='dotnet test --logger "trx"'
alias dlr='dotnet list package --outdated'
# 使用 dotnet watch 开发(热重载)
dotnet watch --project ./src/MyApi
# 文件变更时自动重新编译和重启
# 支持 --filter 排除文件
# 使用 dotnet user-secrets 管理开发密钥
dotnet user-secrets init --project ./src/MyApi
dotnet user-secrets set "ConnectionStrings:Default" "Server=.;Database=MyDb" --project ./src/MyApi
dotnet user-secrets list --project ./src/MyApi
dotnet user-secrets remove "ConnectionStrings:Default" --project ./src/MyApi性能分析工具
# dotnet-counters:实时监控运行时指标
dotnet tool install --global dotnet-counters
dotnet-counters monitor --process-id <PID>
# dotnet-dump:生成和分析内存转储
dotnet tool install --global dotnet-dump
dotnet-dump collect --process-id <PID>
dotnet-dump analyze dump.dmp
# dotnet-gcdump:生成 GC 堆转储(比完整 dump 小得多)
dotnet tool install --global dotnet-gcdump
dotnet-gcdump collect --process-id <PID>
# dotnet-trace:收集性能追踪
dotnet tool install --global dotnet-trace
dotnet-trace collect --process-id <PID> --duration 00:00:30
dotnet-trace collect --profile cpu-sampling --process-id <PID>
# dotnet-sos:安装 SOS 调试扩展
dotnet tool install --global dotnet-sos
dotnet-sos install性能分析工具使用场景:
- dotnet-counters: 快速查看 CPU、内存、GC、线程池等运行时指标
- dotnet-dump: 分析内存泄漏、死锁和崩溃问题
- dotnet-gcdump: 分析托管堆上的对象分布,定位内存占用热点
- dotnet-trace: 分析 CPU 性能瓶颈和方法执行时间
- 建议在生产环境预安装这些工具,故障发生时可以立即使用
- 在 Docker 中使用需要安装诊断工具并设置适当权限dotnet watch 与开发效率
# 基本用法:文件变更时自动重新编译运行
dotnet watch --project ./src/MyApi
# 热重载(.NET 6+ 默认开启)
# 修改代码后自动应用变更,无需重启应用
dotnet watch --project ./src/MyApi --hot-reload
# 禁用热重载(每次变更都重启)
dotnet watch --project ./src/MyApi --no-hot-reload
# 监听文件变更时运行测试
dotnet watch test --project ./tests/MyTests
# 指定要监听的文件(排除某些文件)
dotnet watch --project ./src/MyApi --exclude "**/wwwroot/**"
# 使用 dotnet user-jwts 创建测试 JWT
dotnet user-jwts create --project ./src/MyApi \
--name "testuser" \
--claim "role=admin" \
--audience "myapi"优点
缺点
总结
.NET CLI 是现代 .NET 开发不可或缺的工具,它提供了从项目创建到部署发布的完整命令行支持。掌握常用命令可以显著提升开发效率,尤其在团队协作和 CI/CD 环境中。建议开发者熟练掌握 dotnet new、dotnet build、dotnet test、dotnet publish 等核心命令,并学会利用全局工具和自定义模板扩展 CLI 的能力。
关键知识点
- 先明确这个主题影响的是语法层、运行时层,还是性能与可维护性层。
- 学习时要同时关注语言表面写法和编译器、JIT、GC 等底层行为。
- 真正有价值的是知道“为什么这样写”和“在什么边界下不能这样写”。
- 框架与语言特性类主题要同时理解运行方式和工程组织方式。
项目落地视角
- 把示例改成最小可运行样例,并观察编译输出、运行结果和异常行为。
- 如果它会进入团队代码规范,最好同步补充命名约定、禁用场景和替代方案。
- 涉及性能结论时,优先用 Benchmark 或实际热点链路验证,而不是凭感觉判断。
- 明确项目入口、配置管理、依赖管理、日志和测试策略。
常见误区
- 只记语法糖,不知道底层成本。
- 把适用于小样例的写法直接搬到高并发或大对象场景里。
- 忽略框架版本、语言版本和运行时差异,导致结论失真。
- 把 notebook 或脚本风格直接带入长期维护项目。
进阶路线
- 继续向源码、IL、JIT 行为和 BCL 实现层深入。
- 把知识点和代码评审、性能诊断、面试复盘结合起来。
- 把同类主题做横向对比,例如值类型与引用类型、迭代器与 async 状态机、反射与 Source Generator。
- 继续补齐部署、打包、监控和性能调优能力。
适用场景
- 当你准备把《.NET CLI 命令行工具》真正落到项目里时,最适合先在一个独立模块或最小样例里验证关键路径。
- 适合在需要理解语言特性、运行时行为或 API 边界时阅读。
- 当代码开始出现性能瓶颈、可维护性问题或语义歧义时,这类主题会直接影响实现质量。
落地建议
- 先写最小可运行样例,再把结论迁移到真实业务代码。
- 同时记录这个特性的收益、限制和替代方案,避免为了“高级”而使用。
- 涉及内存、并发或序列化时,最好配合调试器或基准测试验证。
排错清单
- 先确认问题属于编译期、运行期还是语义误用。
- 检查是否存在隐式转换、装箱拆箱、闭包捕获或上下文切换等隐藏成本。
- 查看异常栈、日志和最小复现代码,优先排除使用姿势问题。
复盘问题
- 如果把《.NET CLI 命令行工具》放进你的当前项目,最先要验证的输入、输出和失败路径分别是什么?
- 《.NET CLI 命令行工具》最容易在什么规模、什么边界条件下暴露问题?你会用什么指标或日志去确认?
- 相比默认实现或替代方案,采用《.NET CLI 命令行工具》最大的收益和代价分别是什么?
