# 为 GitHub Codespaces 设置 C# （.NET） 项目

通过创建自定义开发容器配置，在 GitHub Codespaces 中开始一个 C# (.NET) 项目。

## 简介

本教程指南介绍如何设置示例 C# （.NET） 项目 在 GitHub Codespaces 中使用 Visual Studio Code web 客户端。 这样会向你演示在 codespace 中打开项目，以及添加和修改预定义开发容器配置的过程。

完成本教程后，你将能够使用 VS Code Web 客户端或 VS Code 桌面应用程序将开发容器配置添加到自己的存储库。

有关开发容器的详细信息，请参阅“[开发容器简介](/zh/enterprise-cloud@latest/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers)”。

## 步骤 1：在 codespace 中打开项目

1. 登录到 GitHub.com（如果尚未登录）。
2. 转到 <https://github.com/microsoft/vscode-remote-try-dotnet。>
3. 单击“使用此模板”，然后单击“在 codespace 中打开”。

   ![屏幕截图显示“使用此模板”按钮和展开的下拉菜单，其中显示了“在 codespace 中打开”选项。](/assets/images/help/repository/use-this-template-button.png)

创建 codespace 时，你的项目是在你专用的远程虚拟机上创建的。 默认情况下，代码空间的容器具有多种语言和运行时，包括.NET。 它还包括一套常见的工具，例如 git、wget、rsync、openssh 和 nano。

可以通过调整 vCPU 和 RAM 的数量、添加点文件来个性化环境或通过修改已安装的工具和脚本来自定义 codespace。 有关详细信息，请参阅“[自定义代码空间](/zh/enterprise-cloud@latest/codespaces/customizing-your-codespace)”。

GitHub Codespaces 使用名为 `devcontainer.json` 的文件来配置在 codespace 中使用的开发容器。 每个存储库可以包含一个或多个 `devcontainer.json` 文件，以便准确提供在 codespace 中处理代码所需的开发环境。

启动时，GitHub Codespaces 使用 `devcontainer.json` 文件以及构成开发容器配置的任何依赖文件来安装工具和运行时，以及执行项目所需的其他安装任务。 有关详细信息，请参阅“[开发容器简介](/zh/enterprise-cloud@latest/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers)”。

## 步骤 2：添加开发容器配置

GitHub Codespaces 的默认开发容器或“开发容器”预先安装了最新的 .NET 版本和常用工具。 但是，我们建议配置自己的开发容器，以包含项目所需的所有工具和脚本。 这将确保存储库中的所有 GitHub Codespaces 用户都拥有完全可复制的环境。

若要将存储库设置为使用自定义开发容器，需要创建一个或多个 `devcontainer.json` 文件。 可以在 Visual Studio Code 中从预定义配置模板中添加这些文件，也可以自行编写。 有关开发容器配置的详细信息，请参阅“[开发容器简介](/zh/enterprise-cloud@latest/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers)”。

1. 访问 Visual Studio Code Command Palette (<kbd>Shift</kbd>+<kbd>Command</kbd>+<kbd>P</kbd> / <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)，然后开始键入“add dev”。 单击“Codespaces: 添加开发容器配置文件”。

   ![命令面板的屏幕截图，其中输入了“add dev”，并列出了“Codespaces: 添加开发容器配置文件”。](/assets/images/help/codespaces/add-prebuilt-container-command.png)

2. 单击“创建新配置”。

3. 在此示例中，创建 codespace 的模板存储库已包含开发容器配置，因此会显示一条消息，告知配置文件已存在。 我们将覆盖现有配置文件，因此请单击“继续”。

4. 单击“显示所有定义”。

   ![“添加开发容器配置文件”下拉菜单的屏幕截图，显示了各种选项，包括“显示所有定义”。](/assets/images/help/codespaces/show-all-definitions.png)

5. 键入 `c#`，然后单击 **C# （.NET）**。 如果项目使用特定工具，则可使用其他选项。 例如 C# 和 MS SQL。

   ![“添加开发容器配置文件”下拉列表的屏幕截图，文本框中输入了“c#”，下面列出了各种 C# 选项。](/assets/images/help/codespaces/add-csharp-prebuilt-container.png)

6. 选择要用于项目的.NET版本。 在本例中，选择标记为“(默认)”的版本。

   ![“添加开发容器配置文件”下拉列表的屏幕截图，其中显示了各种.NET版本，包括“7.0（默认值）。](/assets/images/help/codespaces/add-dotnet-version.png)

7. 将显示附加功能列表。 我们将安装 .NET CLI，这是一个命令行接口，用于开发、生成、运行和发布.NET应用程序。 要安装此工具，请键入 `dotnet`，选择 `Dotnet CLI`，然后单击“确定”。

   ![“添加开发容器配置文件”下拉列表的屏幕截图，其中显示了文本框中的“dotnet”和下拉列表中的“Dotnet CLI”。](/assets/images/help/codespaces/add-dotnet-features.png)

8. 一条消息会显示，告知开发容器配置文件已存在。 单击“覆盖”。

   创建 `devcontainer.json` 文件并在编辑器中打开。

### 自定义开发容器配置的详细信息

如果在 Visual Studio Code 资源管理器中查看，将看到一个 `.devcontainer` 目录已添加到包含 `devcontainer.json` 文件的项目存储库的根目录中。 这是从此存储库创建的 codespace 的主配置文件。

#### devcontainer.json

已添加的 `devcontainer.json` 文件将包含 `name`、`image` 和 `features` 属性的值。 包含一些可能有用的其他属性，但已注释掉。

文件类似于下面所示，具体取决于你选择的映像：

```jsonc
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet
{
  "name": "C# (.NET)",
  // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
  "image": "mcr.microsoft.com/devcontainers/dotnet:0-7.0",
  "features": {
    "ghcr.io/devcontainers/features/dotnet:1": {}
  }

  // Features to add to the dev container. More info: https://containers.dev/features.
  // "features": {},

  // Use 'forwardPorts' to make a list of ports inside the container available locally.
  // "forwardPorts": [5000, 5001],
  // "portsAttributes": {
  //   "5001": {
  //     "protocol": "https"
  //   }
  // }

  // Use 'postCreateCommand' to run commands after the container is created.
  // "postCreateCommand": "dotnet restore",

  // Configure tool-specific properties.
  // "customizations": {},

  // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
  // "remoteUser": "root"
}
```

* **名称：** 你可以将开发容器命名为任意名称。 提供了默认值。
* **图像：** 容器注册表（[DockerHub](https://hub.docker.com/)[GitHubContainer registry](/zh/enterprise-cloud@latest/packages/learn-github-packages/introduction-to-github-packages) 或 [Azure 容器注册表](https://azure.microsoft.com/services/container-registry/)）中用于为代码空间创建开发容器的映像的名称。
* 功能：一个或多个对象的列表，其中每个对象引用一个可用的开发容器功能。 功能是安装代码和开发容器配置的独立、可共享单元。 它们提供了一种简单的方法，可将更多工具、运行时或库功能添加到开发容器。 您可以在 VS Code 中或在 `devcontainer.json` 上的 GitHub 编辑器中添加功能。 有关更多信息，请单击 Visual Studio Code 中的 \*\*\*\*\*\*\*\* 或 [Web browser](/zh/enterprise-cloud@latest/codespaces/setting-up-your-project-for-codespaces/configuring-dev-containers/adding-features-to-a-devcontainer-file?tool=webui) 选项卡。
* **forwardPorts:** 此处列出的所有端口都会自动转发。 有关详细信息，请参阅“[代码空间中的转发端口](/zh/enterprise-cloud@latest/codespaces/developing-in-a-codespace/forwarding-ports-in-your-codespace)”。
* **portsAttributes** - 此属性将指定的端口映射到一个或多个默认选项。 有关详细信息，请参阅开发容器网站上的[开发容器规范](https://containers.dev/implementors/json_reference/#port-attributes)。
* postCreateCommand：使用此属性在创建 codespace 后运行命令。 这可以格式化为字符串（如上所示）、数组或对象。 有关详细信息，请参阅开发容器网站上的[开发容器规范](https://containers.dev/implementors/json_reference/#lifecycle-scripts)。
* 自定义：此属性允许你在 codespace 中使用特定工具或服务时自定义它。 例如，可以为 VS Code 配置特定设置和扩展。 有关详细信息，请参阅开发容器网站上的“[支持工具和服务](https://containers.dev/supporting)”。
* remoteUser：默认情况下以 vscode 用户身份运行，但可以选择将其设置为 root。

有关可用属性的完整列表，请参阅开发容器网站上的[开发容器规范](https://containers.dev/implementors/json_reference/)。

#### 其他开发容器配置文件

如果你熟悉 Docker，除 `devcontainer.json` 文件外，你还可能需要使用 Dockerfile 或 Docker Compose 来配置 codespace 环境。 可以通过在 `devcontainer.json` 文件旁边添加 `Dockerfile` 或 `compose.yaml` 文件来实现这一点。 有关详细信息，请参阅开发容器网站上的“[使用映像、Dockerfile 和 Docker Compose](https://containers.dev/guide/dockerfile)”。

## 步骤 3：修改 devcontainer.json 文件

添加了开发容器配置并基本了解所有功能之后，现在可以进行更改以进一步自定义你的环境。 在此示例中，你将添加执行以下操作的属性：

* 将远程计算机上运行应用程序的端口转发到本地计算机。
* 创建开发容器后运行 `dotnet restore` 以还原应用程序所需的依赖项。
* 在此 codespace 中自动安装 VS Code 扩展。

1. 在 `devcontainer.json` 文件的 `features` 属性后添加逗号，删除关于功能的两个取消注释行。

   ```jsonc copy
     "features": {
       "ghcr.io/devcontainers/features/dotnet:1": {}
     },

     // Features to add to the dev container. More info: https://containers.dev/features.
     // "features": {},
   ```

2. 取消注释 `forwardPorts` 属性，并将其值仅更改为端口 `5000`。

   ```jsonc copy
   // Use 'forwardPorts' to make a list of ports inside the container available locally.
   "forwardPorts": [5000],
   ```

3. 取消注释 `postCreateCommand` 属性。

   ```jsonc copy
   // Use 'postCreateCommand' to run commands after the container is created.
   "postCreateCommand": "dotnet restore",
   ```

4. 取消注释 `customizations` 属性并按如下所示对其进行编辑，以安装“代码拼写检查器”VS Code 扩展。

   ```jsonc copy
   // Configure tool-specific properties.
   "customizations": {
     // Configure properties specific to VS Code.
     "vscode": {
       // Add the IDs of extensions you want installed when the container is created.
       "extensions": [
         "streetsidesoftware.code-spell-checker"
       ]
     }
   }
   ```

   文件 `devcontainer.json` 现在应如下所示，具体取决于你选择的图像：

   ```jsonc
   // For format details, see https://aka.ms/devcontainer.json. For config options, see the
   // README at: https://github.com/devcontainers/templates/tree/main/src/dotnet
   {
     "name": "C# (.NET)",
     // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
     "image": "mcr.microsoft.com/devcontainers/dotnet:0-7.0",
     "features": {
       "ghcr.io/devcontainers/features/dotnet:1": {}
     },

     // Use 'forwardPorts' to make a list of ports inside the container available locally.
     "forwardPorts": [5000],
     // "portsAttributes": {
     //   "5001": {
     //     "protocol": "https"
     //   }
     // }

     // Use 'postCreateCommand' to run commands after the container is created.
     "postCreateCommand": "dotnet restore",

     // Configure tool-specific properties.
     "customizations": {
       // Configure properties specific to VS Code.
       "vscode": {
         // Add the IDs of extensions you want installed when the container is created.
         "extensions": [
           "streetsidesoftware.code-spell-checker"
         ]
       }
     }

     // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
     // "remoteUser": "root"
   }
   ```

5. 保存所做更改。

6. 访问 VS Code Command Palette (<kbd>Shift</kbd>+<kbd>Command</kbd>+<kbd>P</kbd> / <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)，然后开始键入“rebuild”。 单击“Codespace: 重生成容器”。

   ![命令面板的屏幕截图，其中包含“重新生成容器”搜索，下拉列表中突出显示了“Codespace: 重新生成容器”选项。](/assets/images/help/codespaces/codespaces-rebuild.png)

   > \[!TIP]
   > 你可能偶尔需要执行一次完整重建，以清除缓存并使用全新的镜像重新构建容器。 有关详细信息，请参阅“[在 codespace 中重新生成容器](/zh/enterprise-cloud@latest/codespaces/developing-in-a-codespace/rebuilding-the-container-in-a-codespace#rebuilding-a-container)”。
   > 在代码空间内进行重建可确保在将更改提交到仓库之前，更改能够按预期工作。 如果某些问题导致了故障，您将进入带有恢复容器的代码空间中，您可以从该容器进行重建以继续调整容器。

   重新生成开发容器且 codespace 再次可用后，`postCreateCommand` 将运行，还原所需的依赖项，并且“代码拼写检查器”扩展将可用。

## 步骤 4：运行应用程序

在上一部分中，你使用 `postCreateCommand` 通过 `dotnet restore` 命令安装了一组包。 现已安装依赖项，可以运行应用程序。

1. 按 `F5` 或在终端中输入 `dotnet watch run` 来运行应用程序。
2. 应用程序启动时，单击“端口”选项卡，右键单击端口 5000，然后单击“在浏览器中打开” 。

   ![“端口”选项卡的屏幕截图，其中显示了右键单击菜单，光标指针指向“在浏览器中打开”选项。](/assets/images/help/codespaces/open-port5000-in-browser.png)

## 步骤 5：提交更改

在对 codespace 进行更改（无论是添加新代码还是更改配置）时，需要提交更改。 将配置更改提交到存储库可确保任何其他从此存储库创建 Codespace 的人都获得相同的配置。 你所做的任何自定义（如添加 VS Code 扩展）都将可供所有用户使用。

在本教程中，你从模板存储库创建了 codespace，因此 codespace 中的代码尚未存储在存储库中。 可以通过将 Current Branch 发布到 GitHub 来创建存储库。

如需相关信息，请参阅 [在代码空间中使用源控制](/zh/enterprise-cloud@latest/codespaces/developing-in-a-codespace/using-source-control-in-your-codespace?tool=webui#publishing-a-codespace-created-from-a-template)。

## 后续步骤

现在，你应该能够将自定义开发容器配置添加到自己的 C# （.NET） 项目。

以下是用于更高级场景的一些额外资源。

* [向 devcontainer.json 文件添加功能](/zh/enterprise-cloud@latest/codespaces/setting-up-your-project-for-codespaces/configuring-dev-containers/adding-features-to-a-devcontainer-file?tool=webui)
* [管理 GitHub Codespaces 的账户专属的机密](/zh/enterprise-cloud@latest/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces)
* [管理 GitHub Codespaces 的 GPG 验证](/zh/enterprise-cloud@latest/codespaces/managing-your-codespaces/managing-gpg-verification-for-github-codespaces)
* [代码空间中的转发端口](/zh/enterprise-cloud@latest/codespaces/developing-in-a-codespace/forwarding-ports-in-your-codespace)