Aplicativo simples baseado em Windows 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 baseado em Windows usando o AWS SDK for .NET

Este tutorial usa o AWS SDK for .NET no Windows com Visual Studio e o.NET Core. O tutorial mostra como usar o SDK para listar os buckets do Amazon S3 que você possui e criar um bucket de forma opcional.

Você executará este tutorial no Windows usando o Visual Studio e o .NET Core. Para outras maneiras de configurar seu ambiente de desenvolvimento, consulte Instale e configure seu conjunto de ferramentas.

Necessário para desenvolvimento no Windows com o Visual Studio e o .NET Core:

  • Microsoft .NET Core 2.1, 3.1 ou posterior

    Isso geralmente é incluído por padrão ao instalar uma versão recente do Visual Studio.

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 Visual Studio e crie um novo projeto que use a versão C# do modelo de aplicativo de console; ou seja, com a descrição: “... para criar um aplicativo de linha de comando que pode ser executado no.NET...”. Nomeie o projeto S3CreateAndList.

    nota

    Não escolha a versão do.NET Framework do modelo de aplicativo de console ou, se escolher, certifique-se de usar o.NET Framework 4.7.2 ou posterior.

  2. Com o projeto recém-criado carregado, escolha Tools, NuGetPackage Manager, Manage NuGet Packages for Solution.

  3. Procure os seguintes NuGet pacotes e instale-os no projeto:AWSSDK.S3,AWSSDK.SecurityToken,AWSSDK.SSO, e AWSSDK.SSOOIDC

    Esse processo instala os NuGet pacotes do gerenciador de NuGet pacotes. Como sabemos exatamente quais NuGet pacotes precisamos para este tutorial, podemos realizar essa etapa agora. Também é bastante comum conhecer os pacotes necessários durante o desenvolvimento. Quando isso acontecer, siga um processo semelhante para instalá-los nesse momento.

  4. Se você pretende executar o aplicativo no prompt de comando, abra um prompt de comando agora e navegue até a pasta que conterá a saída de compilação. Normalmente, isso é algo como S3CreateAndList\S3CreateAndList\bin\Debug\net6.0, mas dependerá do seu ambiente.

Criar o código

  1. No projeto S3CreateAndList, localize e abra Program.cs no IDE.

  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; } } }
  3. Compile o aplicativo.

    nota

    Se estiver usando uma versão mais antiga do Visual Studio, você pode receber um erro de compilação semelhante ao seguinte:

    “O atributo 'async main' não está disponível no C# 7.0. Use a versão 7.1 ou superior da linguagem.”

    Se você receber esse erro, configure seu projeto para usar uma versão posterior da linguagem. Isso normalmente é feito nas propriedades do projeto, Build, Advanced.

Execute o aplicativo

  1. Execute o aplicativo sem argumentos de linha de comando. Faça isso no prompt de comando (se você abriu um anteriormente) ou no IDE.

  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-winvs-” como base e adicione algo exclusivo a ela, 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 aplicativo novamente, desta vez fornecendo o nome do bucket.

    Na linha de comando, substitua BUCKET-NAME no comando a seguir pelo nome do bucket que você escolheu.

    S3CreateAndList BUCKET-NAME

    Ou, se você estiver executando o aplicativo no IDE, escolha Projeto, CreateAndList Propriedades do S3, Depurar e insira o nome do bucket lá.

  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.