

的版本 4 (V4) 适用于 .NET 的 AWS SDK 已经发布！

有关重大更改和迁移应用程序的信息，请参阅[迁移主题](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 开始使用 适用于 .NET 的 AWS SDK
<a name="net-dg-config"></a>

了解如何安装、设置和使用 适用于 .NET 的 AWS SDK。您必须安装工具链，并设置应用程序访问 AWS 服务所需的许多基本内容。这些指令包括：
+ 适当的用户账户或角色
+ 该用户账户或代入该角色的用户账户的身份验证信息

有关如何配置项目和其他关键部分的信息，请参阅[配置 适用于 .NET 的 AWS SDK](configuring-the-sdk.md)。

**Topics**
+ [安装和配置您的工具链](net-dg-dev-env.md)
+ [使用进行身份验证 AWS](creds-idc.md)
+ [创建简单的应用程序](quick-start.md)

# 安装和配置您的工具链 适用于 .NET 的 AWS SDK
<a name="net-dg-dev-env"></a>

要使用 适用于 .NET 的 AWS SDK，必须安装某些开发工具。

## 跨平台开发
<a name="net-dg-dev-env-cross"></a>

对于 Windows、Linux 或 macOS 上的跨平台 .NET 开发，需要具备：
+ Microsoft [.NET Core 开发工具包](https://learn.microsoft.com/en-us/dotnet/fundamentals/)，版本 2.1、3.1 或更高版本，其中包括 .NET 命令行界面 (CLI) (**`dotnet`**) 和 .NET Core 运行时。
+ 适合您的操作系统和要求的代码编辑器或集成式开发环境（IDE）。这通常为 .NET Core 提供一些支持。

  例子包括[微软 Visual Studio Code（VS Code）](https://code.visualstudio.com/)、[JetBrains Rider](https://www.jetbrains.com/rider/) 和[微软 Visual Studio](https://visualstudio.microsoft.com/vs/)。
+ （可选）一个 AWS 工具包（如果有）适用于您选择的编辑器和操作系统。

  示例包括 [AWS Toolkit for Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)、[AWS Toolkit for JetBrains](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) 和 [AWS Toolkit for Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)。

## 在 Windows 上使用 Visual Studio 和 .NET Core 开发
<a name="net-dg-dev-env-winvs"></a>

对于在 Windows 使用 Visual Studio 和 .NET Core 进行开发，需要以下项：
+ [Microsoft Visual Studio](https://visualstudio.microsoft.com/vs/)
+ Microsoft .NET Core 2.1、3.1 或更高版本

  默认情况下，安装最新版本的 Visual Studio 时通常会包含此功能。
+ （可选） AWS Toolkit for Visual Studio，它是一个插件，它提供了一个用户界面，用于管理 Visual Studio 中的 AWS 资源和本地配置文件。要安装该工具包，请参阅[AWS Toolkit for Visual Studio设置](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/getting-set-up.html)。

  有关更多信息，请参阅 [AWS Toolkit for Visual Studio 《用户指南》](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/)。

## 后续步骤
<a name="net-dg-dev-env-next"></a>

[使用进行身份验证 适用于 .NET 的 AWS SDK AWS](creds-idc.md)

# 使用进行身份验证 适用于 .NET 的 AWS SDK AWS
<a name="creds-idc"></a>

使用开发 AWS 时，您必须确定您的代码是如何进行身份验证的。 AWS 服务您可以通过不同的方式配置对 AWS 资源的编程访问权限，具体取决于环境和可用的 AWS 访问权限。

要查看 SDK 的各种身份验证方法，请参阅《工具参考指南》[和《*工具参考指南》中的身份验证AWS SDKs 和*访问权限](https://docs.aws.amazon.com/sdkref/latest/guide/access.html)。

本主题假设新用户正在本地开发，雇主未向其提供身份验证方法，并将使用该用户 AWS IAM Identity Center 来获取临时证书。如果您的环境与这些假设不符，则本主题中的某些信息可能不适用于您，或者某些信息可能已经提供给您。

 配置此环境需要几个步骤，总结如下：

1. [使用控制台凭据登录](#login-con-creds)

1. [启用和配置 IAM Identity Center](#idc-config-sso)

1. [将开发工具包配置为使用 IAM Identity Center。](#idc-config-sdk)

1. [启动 AWS 访问门户会话](#idc-start-portal)

## 使用控制台凭据登录
<a name="login-con-creds"></a>

您可以使用现有的 AWS 管理控制台登录凭据以编程方式访问 AWS 服务。在基于浏览器的身份验证流程之后， AWS 生成可在本地开发工具（如 CL AWS I AWS Tools for PowerShell 和适用于.NET 的 AWS SDK v4）上使用的临时证书。

通过此流程，您可以使用在初始账户设置期间创建的根证书、IAM 用户或身份提供商提供的联合身份以及 AWS CLI 进行身份验证，或者 AWS Tools for PowerShell 自动为您管理临时证书。这种方法无需在本地存储长期凭证，从而增强了安全性。当您从中运行 `Invoke-AWSLogin ` cmdlet AWS Tools for PowerShell 或从 CL AWS I 运行`aws login`命令时，您可以从活动控制台会话中进行选择，也可以通过基于浏览器的身份验证流程登录，这将自动生成临时证书。临时凭证令牌将在 15 分钟后过期，但是在您的请求期间，适用于.NET v4 的 AWS SDK 会在需要时自动刷新令牌。

**重要**  
如果您使用控制台凭据进行身份验证，则您的应用程序必须引用以下 NuGet 软件包，这样 AWS 登录解析才能起作用：  
**AWSSDK. 登录**
未能引用这些程序包将导致运行时系统异常。
+ [AWS Tools for PowerShell 登录凭据《开发者指南》。](https://docs.aws.amazon.com/powershell/v5/userguide/creds-idc.html#login-con-creds)
+ [使用 AWS CLI 使用控制台凭据登录进行 AWS 本地开发。](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html)

按照上面给出的 AWS Tools for PowerShell 或 AWS CLI 步骤登录后，`config`文件将如下所示。

```
[default]
login_session = arn:aws:iam::0123456789012:user/username
region = us-east-1

[my-dev-profile]
login_session = arn:aws:iam::0123456789012:user/username
region = us-east-1
```

## 启用和配置 IAM Identity Center
<a name="idc-config-sso"></a>

要使用 IAM Identity Center，必须先启用并进行配置。要详细了解如何为 SDK 执行此操作，请查看*AWS SDKs 和工具参考指南*中 [IAM Identity Center 身份验证](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html)主题中的**步骤 1**。具体而言，请按照**我没有通过 IAM Identity Center 确立访问权限**下的所有必要说明进行操作。

## 将开发工具包配置为使用 IAM Identity Center。
<a name="idc-config-sdk"></a>

有关如何配置软件开发工具包以使用 IAM Identity Center 的信息，请参阅《*工具参考指南》*中 [IAM 身份中心身份验证](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html)主题的**步骤 2**。AWS SDKs 完成此配置后，您的系统应包含以下元素：
+  AWS CLI，用于在运行应用程序之前启动 AWS 访问门户会话。
+ 共享 AWS `config`文件，其中包含一个[`[default]`配置](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#file-format-profile)文件，其中包含一组可从 SDK 中引用的配置值。要查找此文件的位置，请参阅*AWS SDKs 和工具参考指南*中的[共享文件的位置](https://docs.aws.amazon.com/sdkref/latest/guide/file-location.html)。在向发送请求之前， 适用于 .NET 的 AWS SDK 使用配置文件的 SSO 令牌提供者获取凭证。 AWS`sso_role_name` 值是与 IAM Identity Center 权限集关联的 IAM 角色，应允许访问您的应用程序中使用的 AWS 服务 。

  以下示例 `config` 文件显示了使用 SSO 令牌提供程序设置的默认配置文件。配置文件的 `sso_session` 设置是指所指定的 `sso-session` 节。该`sso-session`部分包含启动 AWS 访问门户会话的设置。

  ```
  [default]
  sso_session = my-sso
  sso_account_id = 111122223333
  sso_role_name = SampleRole
  region = us-east-1
  output = json
  
  [sso-session my-sso]
  sso_region = us-east-1
  sso_start_url = https://provided-domain.awsapps.com/start
  sso_registration_scopes = sso:account:access
  ```

**重要**  
如果您使用 AWS IAM Identity Center 进行身份验证，则您的应用程序必须引用以下 NuGet软件包，这样 SSO 解析才能起作用：  
`AWSSDK.SSO`
`AWSSDK.SSOOIDC`
未能引用这些程序包将导致*运行时系统*异常。

## 启动 AWS 访问门户会话
<a name="idc-start-portal"></a>

在运行可访问的应用程序之前 AWS 服务，您需要为软件开发工具包进行有效的 AWS 访问门户会话，才能使用 IAM Identity Center 身份验证来解析证书。根据配置的会话时长，访问权限最终将过期，并且开发工具包将遇到身份验证错误。要登录 AWS 访问门户，请在中运行以下命令 AWS CLI。

```
aws sso login
```

由于您有默认的配置文件设置，因此无需使用 `--profile` 选项调用该命令。如果您的 SSO 令牌提供程序配置在使用指定的配置文件，则命令为 `aws sso login --profile named-profile`。

要测试是否已有活动会话，请运行以下 AWS CLI 命令。

```
aws sts get-caller-identity
```

对此命令的响应应该报告共享 `config` 文件中配置的 IAM Identity Center 账户和权限集。

**注意**  
如果您已经有一个有效的 AWS 访问门户会话并且`aws sso login`正在运行，则无需提供凭据。  
登录过程可能会提示您允许 AWS CLI 访问您的数据。由于 AWS CLI 是在适用于 Python 的 SDK 之上构建的，因此权限消息可能包含`botocore`名称的变体。

## 附加信息
<a name="idc-additional-info"></a>
+ 有关在开发环境中使用 IAM Identity Center 和 SSO 的更多信息，请参阅[高级身份验证](advanced-auth.md)部分中的[单点登录](sso.md)。此信息包括替代方法和更高级的方法，以及向您展示如何使用这些方法的教程。
+ 有关 SDK 身份验证的更多选项，例如配置文件和环境变量的使用，请参阅*AWS SDKs 和工具参考指南*中的[配置](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)章节。
+ 有关最佳实践的更多信息，请参阅《IAM 用户指南》**中的 [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。
+ 要创建短期 AWS 证书，请参阅 *IAM 用户指南*中的[临时安全证书](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)。
+ 要了解其他凭证提供商，请参阅《*工具参考*指南》AWS SDKs 中的[标准化凭证提供商](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)。

# 使用创建简单的应用程序 适用于 .NET 的 AWS SDK
<a name="quick-start"></a>

本部分为不熟悉 适用于 .NET 的 AWS SDK的开发人员提供了基本教程。

**注意**  
在使用这些教程之前，必须先[安装工具链](net-dg-dev-env.md)并[配置开发工具包身份验证](creds-idc.md)。

有关为特定 AWS 服务开发软件的信息以及代码示例，请参见[呼叫 AWS 服务](working-with-aws-services.md)。有关其他代码示例，请参阅 [适用于 .NET 的 SDK (v4) 代码示例](csharp_code_examples.md)。

**Topics**
+ [简单跨平台应用程序](quick-start-s3-1-cross.md)
+ [基于 Windows 的简单应用程序](quick-start-s3-1-winvs.md)
+ [

# 后续步骤
](quick-start-next-steps.md)

# 简单的跨平台应用程序使用 适用于 .NET 的 AWS SDK
<a name="quick-start-s3-1-cross"></a>

本教程使用 适用于 .NET 的 AWS SDK 和.NET Core 进行跨平台开发。本教程向您展示如何使用开发工具包列出您拥有的 [Amazon S3 桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)，并且可以选择创建新桶。

您将使用跨平台工具（例如 .NET 命令行界面 (CLI)）完成本教程。有关配置开发环境的其它方法，请参阅[安装和配置您的工具链 适用于 .NET 的 AWS SDK](net-dg-dev-env.md)。

**对于 Windows、Linux 或 macOS 上的跨平台 .NET 开发，需要：**
+ Microsoft [.NET Core 开发工具包](https://learn.microsoft.com/en-us/dotnet/fundamentals/)，版本 2.1、3.1 或更高版本，其中包括 .NET 命令行界面 (CLI) (**`dotnet`**) 和 .NET Core 运行时。
+ 适合您的操作系统和要求的代码编辑器或集成式开发环境（IDE）。这通常为 .NET Core 提供一些支持。

  例子包括[微软 Visual Studio Code（VS Code）](https://code.visualstudio.com/)、[JetBrains Rider](https://www.jetbrains.com/rider/) 和[微软 Visual Studio](https://visualstudio.microsoft.com/vs/)。

**注意**  
在使用这些教程之前，必须先[安装工具链](net-dg-dev-env.md)并[配置开发工具包身份验证](creds-idc.md)。

## 步骤
<a name="s3-1-cross-steps"></a>
+ [创建项目](#s3-1-cross-create-project)
+ [创建代码](#s3-1-cross-code)
+ [运行应用程序](#s3-1-cross-run)
+ [清理](#s3-1-cross-clean-up)

## 创建项目
<a name="s3-1-cross-create-project"></a>

1. 打开命令提示符或终端。查找或创建可以在其中创建 .NET 项目的操作系统文件夹。

1. 在该文件夹中，运行以下命令以创建 .NET 项目。

   ```
   dotnet new console --name S3CreateAndList
   ```

1. 转到新创建的 `S3CreateAndList` 文件夹并运行以下命令。

   ```
   dotnet add package AWSSDK.S3
   dotnet add package AWSSDK.SecurityToken
   dotnet add package AWSSDK.SSO
   dotnet add package AWSSDK.SSOOIDC
   ```

   前面的命令通过 NuGet 软件包[管理器安装NuGet 软件包](https://www.nuget.org/profiles/awsdotnet)。因为我们确切地知道本教程需要什么 NuGet 软件包，所以我们现在可以执行这个步骤了。在开发过程中，知道所需的程序包也很常见。出现这种情况时，可以运行类似的命令。

## 创建代码
<a name="s3-1-cross-code"></a>

1. 在 `S3CreateAndList` 文件夹中，查找并在代码编辑器中打开 `Program.cs`。

1. 用以下代码替换内容并保存文件。

   ```
   using System;
   using System.Threading.Tasks;
   
   // NuGet packages: AWSSDK.S3, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC
   using Amazon.Runtime;
   using Amazon.Runtime.CredentialManagement;
   using Amazon.S3;
   using Amazon.S3.Model;
   using Amazon.SecurityToken;
   using Amazon.SecurityToken.Model;
   
   namespace S3CreateAndList
   {
       class Program
       {
           // This code is part of the quick tour in the developer guide.
           // See https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/quick-start.html
           // for complete steps.
           // Requirements:
           // - An SSO profile in the SSO user's shared config file with sufficient privileges for
   		//   STS and S3 buckets.
           // - An active SSO Token.
           //    If an active SSO token isn't available, the SSO user should do the following:
           //    In a terminal, the SSO user must call "aws sso login".
   
           // Class members.
           static async Task Main(string[] args)
           {
               // Get SSO credentials from the information in the shared config file.
               // For this tutorial, the information is in the [default] profile.
               var ssoCreds = LoadSsoCredentials("default");
   
               // Display the caller's identity.
               var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds);
               Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}");
   
               // Create the S3 client is by using the SSO credentials obtained earlier.
               var s3Client = new AmazonS3Client(ssoCreds);
   
               // Parse the command line arguments for the bucket name.
               if (GetBucketName(args, out String bucketName))
               {
                   // If a bucket name was supplied, create the bucket.
                   // Call the API method directly
                   try
                   {
                       Console.WriteLine($"\nCreating bucket {bucketName}...");
                       var createResponse = await s3Client.PutBucketAsync(bucketName);
                       Console.WriteLine($"Result: {createResponse.HttpStatusCode.ToString()}");
                   }
                   catch (Exception e)
                   {
                       Console.WriteLine("Caught exception when creating a bucket:");
                       Console.WriteLine(e.Message);
                   }
               }
   
               // Display a list of the account's S3 buckets.
               Console.WriteLine("\nGetting a list of your buckets...");
               var listResponse = await s3Client.ListBucketsAsync();
               Console.WriteLine($"Number of buckets: {listResponse.Buckets.Count}");
               foreach (S3Bucket b in listResponse.Buckets)
               {
                   Console.WriteLine(b.BucketName);
               }
               Console.WriteLine();
           }
   
           // 
           // Method to parse the command line.
           private static Boolean GetBucketName(string[] args, out String bucketName)
           {
               Boolean retval = false;
               bucketName = String.Empty;
               if (args.Length == 0)
               {
                   Console.WriteLine("\nNo arguments specified. Will simply list your Amazon S3 buckets." +
                     "\nIf you wish to create a bucket, supply a valid, globally unique bucket name.");
                   bucketName = String.Empty;
                   retval = false;
               }
               else if (args.Length == 1)
               {
                   bucketName = args[0];
                   retval = true;
               }
               else
               {
                   Console.WriteLine("\nToo many arguments specified." +
                     "\n\ndotnet_tutorials - A utility to list your Amazon S3 buckets and optionally create a new one." +
                     "\n\nUsage: S3CreateAndList [bucket_name]" +
                     "\n - bucket_name: A valid, globally unique bucket name." +
                     "\n - If bucket_name isn't supplied, this utility simply lists your buckets.");
                   Environment.Exit(1);
               }
               return retval;
           }
   
           //
           // Method to get SSO credentials from the information in the shared config file.
           static AWSCredentials LoadSsoCredentials(string profile)
           {
               var chain = new CredentialProfileStoreChain();
               if (!chain.TryGetAWSCredentials(profile, out var credentials))
                   throw new Exception($"Failed to find the {profile} profile");
               return credentials;
           }
       }
   
       // Class to read the caller's identity.
       public static class Extensions
       {
           public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient)
           {
               var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());
               return response.Arn;
           }
       }
   }
   ```

## 运行应用程序
<a name="s3-1-cross-run"></a>

1. 运行以下命令。

   ```
   dotnet run
   ```

1. 检查输出以查看您拥有的 Amazon S3 桶数（如果有）及其名称。

1. 为新 Amazon S3 桶选择名称。使用 “dotnet-quicktour-s3-1-cross-” 作为基础，然后为其添加一些独特的东西，例如 GUID 或你的名字。请务必遵守存储桶命名规则，如 [Amazon S3 用户指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)中的[存储桶命名规则](https://docs.aws.amazon.com/AmazonS3/latest/userguide/BucketRestrictions.html#bucketnamingrules)中所述。

1. 运行以下命令，*amzn-s3-demo-bucket*替换为您选择的存储桶的名称。

   ```
   dotnet run amzn-s3-demo-bucket
   ```

1. 检查输出以查看创建的新存储桶。

## 清理
<a name="s3-1-cross-clean-up"></a>

执行本教程时，您创建了一些可选择在此时清理的资源。
+ 如果您不想保留应用程序在之前步骤中创建的存储桶，请使用位于的 Amazon S3 控制台将其删除[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。
+ 如果您不想保留您的 .NET 项目，请从开发环境中删除 `S3CreateAndList` 文件夹。

## 后续工作
<a name="s3-1-cross-next"></a>

返回[快速指南菜单](quick-start.md)或直接转到[此快速指南的末尾](quick-start-next-steps.md)。

# 基于 Windows 的简单应用程序使用 适用于 .NET 的 AWS SDK
<a name="quick-start-s3-1-winvs"></a>

本教程使用了 Windows 适用于 .NET 的 AWS SDK 上的 Visual Studio 和.NET Core。本教程向您展示如何使用开发工具包列出您拥有的 [Amazon S3 桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)，并且可以选择创建新桶。

您将在 Windows 上使用 Visual Studio 和 .NET Core 完成本教程。有关配置开发环境的其它方法，请参阅[安装和配置您的工具链 适用于 .NET 的 AWS SDK](net-dg-dev-env.md)。

**对于在 Windows 使用 Visual Studio 和 .NET Core 进行开发，需要：**
+ [Microsoft Visual Studio](https://visualstudio.microsoft.com/vs/)
+ Microsoft .NET Core 2.1、3.1 或更高版本

  默认情况下，安装最新版本的 Visual Studio 时通常会包含此功能。

**注意**  
在使用这些教程之前，必须先[安装工具链](net-dg-dev-env.md)并[配置开发工具包身份验证](creds-idc.md)。

## 步骤
<a name="s3-1-winvs-steps"></a>
+ [创建项目](#s3-1-winvs-create-project)
+ [创建代码](#s3-1-winvs-code)
+ [运行应用程序](#s3-1-winvs-run)
+ [清理](#s3-1-winvs-clean-up)

## 创建项目
<a name="s3-1-winvs-create-project"></a>

1. 打开 Visual Studio 并创建一个使用 C\$1 版本的**控制台应用程序**模板的新项目；也就是说，描述为：“... 用于创建可以在.NET 上运行的命令行应用程序...”。将项目命名为 `S3CreateAndList`。
**注意**  
不要选择控制台应用程序模板的.NET Framework 版本，或者，如果选择了，请务必使用.NET Framework 4.7.2 或更高版本。

1. 加载新创建的项目后，选择 “**工具**”、“Pack NuGet age **Manager**”、“**管理解决方案 NuGet 包**”。

1. 浏览以下 NuGet 软件包并将其安装到项目中：`AWSSDK.S3``AWSSDK.SecurityToken`、`AWSSDK.SSO`、和 `AWSSDK.SSOOIDC`

   此过程通过 NuGet 软件包[管理器安装NuGet 软件包](https://www.nuget.org/profiles/awsdotnet)。因为我们确切地知道本教程需要什么 NuGet 软件包，所以我们现在可以执行这个步骤了。在开发过程中，知道所需的程序包也很常见。出现这种情况时，请按照类似的过程安装它们。

1. 如果您打算从命令符提示处运行应用程序，请立即打开命令提示符并导航到将包含构建输出的文件夹。这通常是类似于 `S3CreateAndList\S3CreateAndList\bin\Debug\net6.0` 的内容，但具体取决于您的环境。

## 创建代码
<a name="s3-1-winvs-code"></a>

1. 在 `S3CreateAndList` 项目中，查找并在 IDE 中打开 `Program.cs`。

1. 用以下代码替换内容并保存文件。

   ```
   using System;
   using System.Threading.Tasks;
   
   // NuGet packages: AWSSDK.S3, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC
   using Amazon.Runtime;
   using Amazon.Runtime.CredentialManagement;
   using Amazon.S3;
   using Amazon.S3.Model;
   using Amazon.SecurityToken;
   using Amazon.SecurityToken.Model;
   
   namespace S3CreateAndList
   {
       class Program
       {
           // This code is part of the quick tour in the developer guide.
           // See https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/quick-start.html
           // for complete steps.
           // Requirements:
           // - An SSO profile in the SSO user's shared config file with sufficient privileges for
   		//   STS and S3 buckets.
           // - An active SSO Token.
           //    If an active SSO token isn't available, the SSO user should do the following:
           //    In a terminal, the SSO user must call "aws sso login".
   
           // Class members.
           static async Task Main(string[] args)
           {
               // Get SSO credentials from the information in the shared config file.
               // For this tutorial, the information is in the [default] profile.
               var ssoCreds = LoadSsoCredentials("default");
   
               // Display the caller's identity.
               var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds);
               Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}");
   
               // Create the S3 client is by using the SSO credentials obtained earlier.
               var s3Client = new AmazonS3Client(ssoCreds);
   
               // Parse the command line arguments for the bucket name.
               if (GetBucketName(args, out String bucketName))
               {
                   // If a bucket name was supplied, create the bucket.
                   // Call the API method directly
                   try
                   {
                       Console.WriteLine($"\nCreating bucket {bucketName}...");
                       var createResponse = await s3Client.PutBucketAsync(bucketName);
                       Console.WriteLine($"Result: {createResponse.HttpStatusCode.ToString()}");
                   }
                   catch (Exception e)
                   {
                       Console.WriteLine("Caught exception when creating a bucket:");
                       Console.WriteLine(e.Message);
                   }
               }
   
               // Display a list of the account's S3 buckets.
               Console.WriteLine("\nGetting a list of your buckets...");
               var listResponse = await s3Client.ListBucketsAsync();
               Console.WriteLine($"Number of buckets: {listResponse.Buckets.Count}");
               foreach (S3Bucket b in listResponse.Buckets)
               {
                   Console.WriteLine(b.BucketName);
               }
               Console.WriteLine();
           }
   
           // 
           // Method to parse the command line.
           private static Boolean GetBucketName(string[] args, out String bucketName)
           {
               Boolean retval = false;
               bucketName = String.Empty;
               if (args.Length == 0)
               {
                   Console.WriteLine("\nNo arguments specified. Will simply list your Amazon S3 buckets." +
                     "\nIf you wish to create a bucket, supply a valid, globally unique bucket name.");
                   bucketName = String.Empty;
                   retval = false;
               }
               else if (args.Length == 1)
               {
                   bucketName = args[0];
                   retval = true;
               }
               else
               {
                   Console.WriteLine("\nToo many arguments specified." +
                     "\n\ndotnet_tutorials - A utility to list your Amazon S3 buckets and optionally create a new one." +
                     "\n\nUsage: S3CreateAndList [bucket_name]" +
                     "\n - bucket_name: A valid, globally unique bucket name." +
                     "\n - If bucket_name isn't supplied, this utility simply lists your buckets.");
                   Environment.Exit(1);
               }
               return retval;
           }
   
           //
           // Method to get SSO credentials from the information in the shared config file.
           static AWSCredentials LoadSsoCredentials(string profile)
           {
               var chain = new CredentialProfileStoreChain();
               if (!chain.TryGetAWSCredentials(profile, out var credentials))
                   throw new Exception($"Failed to find the {profile} profile");
               return credentials;
           }
       }
   
       // Class to read the caller's identity.
       public static class Extensions
       {
           public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient)
           {
               var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());
               return response.Arn;
           }
       }
   }
   ```

1. 构建应用程序。
**注意**  
如果您使用的是旧版 Visual Studio，则可能会遇到类似以下内容的构建错误：  
“Feature 'async main' is not available in C\$1 7.0. Please use language version 7.1 or greater.”  
如果您遇到此错误，请将项目设置为使用该语言的更高版本。这通常在项目属性**构建**、**高级**中完成。

## 运行应用程序
<a name="s3-1-winvs-run"></a>

1. 不带命令行参数运行应用程序。在命令提示符中（如果之前已打开）或从 IDE 执行此操作。

1. 检查输出以查看您拥有的 Amazon S3 桶数（如果有）及其名称。

1. 为新 Amazon S3 桶选择名称。使用 “dotnet-quicktour-s3-1-winvs-” 作为基础，然后为其添加一些独特的东西，例如 GUID 或你的名字。请务必遵守存储桶命名规则，如 [Amazon S3 用户指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)中的[存储桶命名规则](https://docs.aws.amazon.com/AmazonS3/latest/userguide/BucketRestrictions.html#bucketnamingrules)中所述。

1. 再次运行应用程序，这次提供存储桶名称。

   在命令行中，将以下命令*amzn-s3-demo-bucket*中的内容替换为您选择的存储桶的名称。

   ```
   S3CreateAndList amzn-s3-demo-bucket
   ```

   或者，如果您在 IDE 中运行应用程序，请选择 “**项目**”、“**S3 CreateAndList 属性**”、“**调试**”，然后在那里输入存储桶名称。

1. 检查输出以查看创建的新存储桶。

## 清理
<a name="s3-1-winvs-clean-up"></a>

执行本教程时，您创建了一些可选择在此时清理的资源。
+ 如果您不想保留应用程序在之前步骤中创建的存储桶，请使用位于的 Amazon S3 控制台将其删除[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。
+ 如果您不想保留您的 .NET 项目，请从开发环境中删除 `S3CreateAndList` 文件夹。

## 后续工作
<a name="s3-1-winvs-next"></a>

返回[快速指南菜单](quick-start.md)或直接转到[此快速指南的末尾](quick-start-next-steps.md)。

# 后续步骤
<a name="quick-start-next-steps"></a>

请务必清理您在完成这些教程时创建的所有遗留资源。这些可能是开发环境中的 AWS 资源或资源，例如文件和文件夹。

既然你已经参观了 适用于 .NET 的 AWS SDK，你可能想[开始你的项目](net-dg-start-new-project.md)。