Aplicativo simples para várias plataformas usando o AWS SDK for .NET - AWS SDK for .NET

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Aplicativo simples para várias plataformas usando o AWS SDK for .NET

Esse tutorial usa o AWS SDK for .NET e o .NET Core para o desenvolvimento entre plataformas. O tutorial mostra como usar o SDK para listar os buckets do Amazon S3que você possui e criar um bucket de forma opcional.

Você executará este tutorial usando ferramentas para várias plataforma, como a interface de linha de comando (CLI) do .NET. Para outras maneiras de configurar seu ambiente de desenvolvimento, consulte Instale e configure seu conjunto de ferramentas.

Necessário para desenvolvimento .NET para várias plataformas no Windows, no Linux ou no macOS:

  • Microsoft .NET Core SDK, versão 2.1, 3.1 ou posterior, que inclua a interface de linha de comando (CLI) do .NET (dotnet) e o tempo de execução do .NET Core.

nota

Antes de usar esses tutoriais, primeiro você deve ter instalado seu conjunto de ferramentas e configurado a autenticação do SDK.

Etapas

Criar o projeto

  1. Abra o prompt de comando ou terminal. Localize ou crie uma pasta do sistema operacional na qual você pode criar um projeto .NET.

  2. Nessa pasta, execute o comando a seguir para criar o projeto .NET.

    dotnet new console --name S3CreateAndList
  3. Vá para a pasta S3CreateAndList recém-criada e execute os comandos a seguir.

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

    O comando anterior instala os pacotes NuGet do gerenciador de pacotes NuGet. Como sabemos exatamente quais pacotes NuGet precisamos para esse tutorial, podemos executar esta etapa agora. Também é bastante comum conhecer os pacotes necessários durante o desenvolvimento. Quando isso acontece, um comando semelhante pode ser executado nesse momento.

Criar o código

  1. Na pasta S3CreateAndList, localize e abra Program.cs no editor de código.

  2. Substitua o conteúdo pelo código a seguir e salve o arquivo.

    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; } } }

Execute o aplicativo

  1. Execute o seguinte comando .

    dotnet run
  2. Examine a saída para ver o número de buckets do Amazon S3 que você possui e seus nomes, se houver.

  3. Escolha um nome para um novo bucket do Amazon S3. Use "dotnet-quicktour-s3-1-cross-" como base e adicione algo exclusivo a ele, como um GUID ou seu nome. Siga as regras para nomes de bucket descritas em Regras de nomeação de bucket no Guia do usuário do Amazon S3.

  4. Execute o comando a seguir, substituindo BUCKET-NAME pelo nome do bucket escolhido.

    dotnet run BUCKET-NAME
  5. Examine a saída para ver o novo bucket que foi criado.

Limpeza

Ao executar este tutorial, você criou alguns recursos que pode escolher para limpar neste momento.

  • Se você não quiser manter o bucket que o aplicativo criou em uma etapa anterior, o exclua usando o console do Amazon S3 em https://console.aws.amazon.com/s3/.

  • Se você não quiser manter seu projeto .NET, remova a pasta S3CreateAndList do seu ambiente de desenvolvimento.

Para onde ir em seguida

Volte para o menu do tour rápido ou vá direto para o final deste tour rápido.