Semplice applicazione basata su Windows che utilizza AWS SDK for .NET - AWS SDK for .NET

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Semplice applicazione basata su Windows che utilizza AWS SDK for .NET

Questo tutorial utilizza Windows con Visual Studio e.NET Core. AWS SDK for .NET Il tutorial mostra come utilizzare l'SDK per elencare i bucket Amazon S3 di cui sei proprietario e, facoltativamente, creare un bucket.

Esegui questo tutorial su Windows utilizzando Visual Studio e.NET Core. Per altri modi di configurare il tuo ambiente di sviluppo, consulta. Installa e configura la tua toolchain

Necessario per lo sviluppo su Windows con Visual Studio e.NET Core:

  • Microsoft.NET Core 2.1, 3.1 o versioni successive

    In genere è incluso per impostazione predefinita quando si installa una versione recente di Visual Studio.

Nota

Prima di utilizzare questi tutorial, è necessario aver installato la toolchain e configurato l'autenticazione SDK.

Fasi

Creazione del progetto

  1. Apri Visual Studio e crea un nuovo progetto che utilizzi la versione C# del modello dell'app Console, ovvero con la descrizione: «... per creare un'applicazione da riga di comando che può essere eseguita su.NET...». Assegnare un nome al progetto S3CreateAndList.

    Nota

    Non scegliere la versione.NET Framework del modello di app per console o, in tal caso, assicurati di utilizzare.NET Framework 4.7.2 o versione successiva.

  2. Con il progetto appena creato caricato, scegli Tools, NuGetPackage Manager, Manage NuGet Packages for Solution.

  3. Cerca i seguenti NuGet pacchetti e installali nel progetto: AWSSDK.S3AWSSDK.SecurityToken,AWSSDK.SSO, e AWSSDK.SSOOIDC

    Questo processo installa i NuGet pacchetti dal gestore di NuGet pacchetti. Poiché sappiamo esattamente di quali NuGet pacchetti abbiamo bisogno per questo tutorial, ora possiamo eseguire questo passaggio. È anche comune che i pacchetti richiesti vengano resi noti durante lo sviluppo. Quando ciò accade, seguire un processo simile per installarli in quel momento.

  4. Se intendi eseguire l'applicazione dal prompt dei comandi, apri subito un prompt dei comandi e vai alla cartella che conterrà l'output della build. In genere si tratta di qualcosa di simileS3CreateAndList\S3CreateAndList\bin\Debug\net6.0, ma dipenderà dall'ambiente in uso.

Creazione del codice

  1. Nel progetto S3CreateAndList, trovare e aprire Program.cs nell'IDE.

  2. Sostituire il contenuto con il seguente codice e salvare il file.

    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. Per compilare l'applicazione

    Nota

    Se usi una versione precedente di Visual Studio, potresti ricevere un errore di compilazione simile al seguente:

    «La funzionalità 'async main' non è disponibile in C# 7.0. Utilizza la versione linguistica 7.1 o successiva.»

    Se ricevi questo errore, configura il progetto per utilizzare una versione successiva della lingua. Questa operazione viene in genere eseguita nelle proprietà del progetto, Build, Advanced.

Esecuzione dell'applicazione.

  1. Eseguire l'applicazione senza argomenti della riga di comando. Fatelo nel prompt dei comandi (se ne avete aperto uno in precedenza) o dall'IDE.

  2. Esamina l'output per vedere il numero di bucket Amazon S3 che possiedi, se ce ne sono, e i relativi nomi.

  3. Scegli un nome per un nuovo bucket Amazon S3. Usa "dotnet-quicktour-s3-1-winvs-» come base e aggiungi qualcosa di unico, come un GUID o il tuo nome. Assicurati di seguire le regole per i nomi dei bucket, come descritto in Rules for Bucket Naming nella Amazon S3 User Guide.

  4. Eseguire di nuovo l'applicazione, questa volta fornendo il nome del bucket.

    Nella riga di comando, sostituisci BUCKET-NAME nel comando seguente con il nome del bucket che hai scelto.

    S3CreateAndList BUCKET-NAME

    Oppure, se stai eseguendo l'applicazione nell'IDE, scegli Project, S3 CreateAndList Properties, Debug e inserisci lì il nome del bucket.

  5. Esaminare l'output per visualizzare il nuovo bucket creato.

Rimozione

Durante l'esecuzione di questo tutorial, hai creato alcune risorse che puoi scegliere di pulire in questo momento.

Fasi successive

Torna al menu del tour rapido o vai direttamente alla fine di questo tour rapido.