Aplicación multiplataforma sencilla que utiliza la herramienta AWS SDK for .NET - AWS SDK for .NET

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Aplicación multiplataforma sencilla que utiliza la herramienta AWS SDK for .NET

En este tutorial se utiliza AWS SDK for .NET y .NET Core para el desarrollo multiplataforma. En el tutorial se muestra cómo utilizar SDK para enumerar los buckets de Amazon S3 que posee y, opcionalmente, crear un bucket.

Llevará a cabo este tutorial utilizando herramientas multiplataforma como la interfaz de la línea de comandos (CLI) .NET. Para ver otras formas de configurar el entorno de desarrollo, consulte Instalación y configuración de la cadena de herramientas.

Necesario para el desarrollo multiplataforma de .NET en Windows, Linux o macOS:

  • Microsoft .NET Core SDK, versión 2.1, 3.1 o posterior, que incluye la interfaz de línea de comandos (CLI) de .NET (dotnet) y el tiempo de ejecución de .NET Core.

nota

Antes de usar estos tutoriales, primero debe haber instalado su cadena de herramientas y haber configurado la autenticación de SDK.

Pasos

Creación del proyecto

  1. Abra un símbolo del sistema o un terminal. Busque o cree una carpeta del sistema operativo en la que pueda crear un proyecto .NET.

  2. En esa carpeta, ejecute el siguiente comando para crear el proyecto .NET.

    dotnet new console --name S3CreateAndList
  3. Vaya a la carpeta S3CreateAndList recién creada y ejecute los siguientes comandos:

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

    Con los comandos anteriores se instalan los paquetes Nuget desde el Administrador de paquetes NuGet. Como sabemos exactamente qué paquetes NuGet necesitamos en este tutorial, podemos realizar este paso ahora. También es común que los paquetes requeridos se conozcan durante el desarrollo. Cuando esto sucede, se puede ejecutar un comando similar en ese momento.

Creación del código

  1. En la carpeta S3CreateAndList, busque y abra Program.cs en su editor de código.

  2. Reemplace el contenido con el siguiente código y guarde el archivo.

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

Ejecución de la aplicación

  1. Ejecute el siguiente comando.

    dotnet run
  2. Examine la salida para ver el número de buckets de Amazon S3 que posee, si los hay, y sus nombres.

  3. Elija un nombre para un nuevo bucket de Amazon S3. Use “dotnet-quicktour-s3-1-cross-” como base y agréguele algo único, como un GUID o su nombre. Asegúrese de seguir las reglas de nomenclatura de bucket, como se describe en Reglas de nomenclatura de buckets en la Guía del usuario de Amazon S3.

  4. Ejecute el siguiente comando, reemplazando BUCKET-NAME por el nombre del bucket elegido.

    dotnet run BUCKET-NAME
  5. Examine la salida para ver el nuevo bucket que se creó.

Limpieza

Mientras realizaba este tutorial, ha creado algunos recursos que puede decidir limpiar en este momento.

  • Si no quiere conservar el bucket que la aplicación creó en un paso anterior, elimínelo mediante la consola de Amazon S3 en https://console.aws.amazon.com/s3/.

  • Si no quiere conservar el proyecto de .NET, elimine la carpeta S3CreateAndList del entorno de desarrollo.

Pasos siguientes

Vuelva al menú de recorrido rápido o vaya directamente al final de este recorrido rápido.