

La AWS SDK per .NET V3 è entrata in modalità manutenzione.

[Ti consigliamo di migrare alla V4.AWS SDK per .NET](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html) Per ulteriori dettagli e informazioni su come eseguire la migrazione, consulta il nostro annuncio sulla modalità di [manutenzione](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/).

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à.

# Accesso AWS Identity and Access Management (IAM) con AWS SDK per .NET
<a name="iam-apis-intro"></a>

I AWS SDK per .NET supporti [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/), che sono un servizio web che consente AWS ai clienti di gestire gli utenti e le autorizzazioni degli utenti in AWS.

Un *utente AWS Identity and Access Management * (IAM) è un'entità in AWS cui crei. L'entità rappresenta una persona o un'applicazione con AWS cui interagisce. Per ulteriori informazioni sugli utenti IAM, consulta [IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) e [IAM and STS Limits](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html) nella IAM User Guide.

Concedi le autorizzazioni a un utente creando una *policy* IAM. La policy contiene un *documento di policy* che elenca le azioni che un utente può eseguire e le risorse su cui tali azioni possono influire. Per ulteriori informazioni sulle policy IAM, consulta [Policies and Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) nella *IAM User Guide*.

**avvertimento**  
Per evitare rischi per la sicurezza, non utilizzare gli utenti IAM per l’autenticazione quando sviluppi software creato ad hoc o lavori con dati reali. Utilizza invece la federazione con un provider di identità come [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html).

## APIs
<a name="w2aac19c15c19c13"></a>

 AWS SDK per .NET Fornisce APIs per i clienti IAM. Ti APIs consentono di lavorare con funzionalità IAM come utenti, ruoli e chiavi di accesso.

Questa sezione contiene un piccolo numero di esempi che mostrano i modelli che è possibile seguire quando si lavora con questi modelli APIs. Per visualizzare il set completo di APIs, consulta l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (e scorri fino a «Amazon. IdentityManagement«).

Questa sezione contiene anche [un esempio](net-dg-hosm.md) che mostra come collegare un ruolo IAM alle istanze Amazon EC2 per semplificare la gestione delle credenziali.

[Gli IAM APIs sono forniti da. AWSSDK IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement) NuGetpacchetto.

## Prerequisiti
<a name="w2aac19c15c19c15"></a>

Prima di iniziare, assicurati di aver [configurato l'ambiente e il progetto](net-dg-config.md). Consulta anche le informazioni contenute in[Funzionalità dell'SDK](net-dg-sdk-features.md).

## Argomenti
<a name="w2aac19c15c19c17"></a>

**Topics**
+ [APIs](#w2aac19c15c19c13)
+ [Prerequisiti](#w2aac19c15c19c15)
+ [Argomenti](#w2aac19c15c19c17)
+ [Creazione di politiche gestite da JSON](iam-policies-create-json.md)
+ [Visualizzazione dei documenti relativi alle policy](iam-policies-display.md)
+ [Concessione dell'accesso con un ruolo](net-dg-hosm.md)

# Creazione di policy gestite da IAM da JSON
<a name="iam-policies-create-json"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET creare una [policy gestita da IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) da un determinato documento di policy in JSON. L'applicazione crea un oggetto client IAM, legge il documento di policy da un file e quindi crea la policy.

**Nota**  
Per un documento di policy di esempio in JSON, consulta le [considerazioni aggiuntive](#iam-policies-create-json-additional) alla fine di questo argomento.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#iam-policies-create-json-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Creare la policy](#iam-policies-create-json-create)
+ [Codice completo](#iam-policies-create-json-complete-code)
+ [Ulteriori considerazioni](#iam-policies-create-json-additional)

## Creare la policy
<a name="iam-policies-create-json-create"></a>

Il seguente frammento crea una policy gestita da IAM con il nome e il documento di policy specificati.

L'esempio [alla fine di questo argomento mostra questo](#iam-policies-create-json-complete-code) frammento in uso.

```
    //
    // Method to create an IAM policy from a JSON file
    private static async Task<CreatePolicyResponse> CreateManagedPolicy(
      IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename)
    {
      return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{
        PolicyName = policyName,
        PolicyDocument = File.ReadAllText(jsonFilename)});
    }
```

## Codice completo
<a name="iam-policies-create-json-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c19c21c17b5b1"></a>

NuGet pacchetti:
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

Elementi di programmazione:
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAM.html)

  Classe [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TIAMServiceClient.html)
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAMModel.html).Modello

  Classe [CreatePolicyRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TCreatePolicyRequest.html)

  Classe [CreatePolicyResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TCreatePolicyResponse.html)

### Il codice
<a name="w2aac19c15c19c21c17b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace IamCreatePolicyFromJson
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create an IAM policy with a given policy document
  class Program
  {
    private const int MaxArgs = 2;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs))
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string policyName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--policy-name");
      string policyFilename =
        CommandLine.GetArgument(parsedArgs, null, "-j", "--json-filename");
      if(   string.IsNullOrEmpty(policyName)
         || (string.IsNullOrEmpty(policyFilename) || !policyFilename.EndsWith(".json")))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create an IAM service client
      var iamClient = new AmazonIdentityManagementServiceClient();

      // Create the new policy
      var response = await CreateManagedPolicy(iamClient, policyName, policyFilename);
      Console.WriteLine($"\nPolicy {response.Policy.PolicyName} has been created.");
      Console.WriteLine($"  Arn: {response.Policy.Arn}");
    }


    //
    // Method to create an IAM policy from a JSON file
    private static async Task<CreatePolicyResponse> CreateManagedPolicy(
      IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename)
    {
      return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{
        PolicyName = policyName,
        PolicyDocument = File.ReadAllText(jsonFilename)});
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: IamCreatePolicyFromJson -p <policy-name> -j <json-filename>" +
        "\n  -p, --policy-name: The name you want the new policy to have." +
        "\n  -j, --json-filename: The name of the JSON file with the policy document.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## Ulteriori considerazioni
<a name="iam-policies-create-json-additional"></a>
+ Di seguito è riportato un esempio di documento di policy che è possibile copiare in un file JSON e utilizzare come input per questa applicazione:

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Id"  : "DotnetTutorialPolicy",
    "Statement" : [
      {
        "Sid" : "DotnetTutorialPolicyS3",
        "Effect" : "Allow",
        "Action" : [
          "s3:Get*",
          "s3:List*"
        ],
        "Resource" : "*"
      },
      {
        "Sid" : "DotnetTutorialPolicyPolly",
        "Effect": "Allow",
        "Action": [
          "polly:DescribeVoices",
          "polly:SynthesizeSpeech"
        ],
        "Resource": "*"
      }
    ]
  }
  ```

------
+ Puoi verificare che la policy sia stata creata cercando nella [console IAM](https://console.aws.amazon.com/iam/home#/policies). Nell'elenco a discesa **Filtra policy**, seleziona **Customer** managed. Elimina la politica quando non è più necessaria.
+  Per ulteriori informazioni sulla creazione delle policy, consulta [Creating IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) Policy e [IAM JSON Policy di riferimento](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html) nella [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/)

# Visualizza il documento relativo alla policy di una policy gestita da IAM
<a name="iam-policies-display"></a>

Questo esempio mostra come utilizzare il AWS SDK per .NET per visualizzare un documento di policy. L'applicazione crea un oggetto client IAM, trova la versione predefinita della policy gestita IAM specificata e quindi visualizza il documento relativo alla policy in JSON.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#iam-policies-display-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Trova la versione predefinita](#iam-policies-display-version)
+ [Visualizza il documento relativo alla policy](#iam-policies-display-doc)
+ [Codice completo](#iam-policies-display-complete-code)

## Trova la versione predefinita
<a name="iam-policies-display-version"></a>

Il seguente frammento trova la versione predefinita della policy IAM specificata.

L'esempio [alla fine di questo argomento mostra questo](#iam-policies-display-complete-code) frammento in uso.

```
    //
    // Method to determine the default version of an IAM policy
    // Returns a string with the version
    private static async Task<string> GetDefaultVersion(
      IAmazonIdentityManagementService iamClient, string policyArn)
    {
      // Retrieve all the versions of this policy
      string defaultVersion = string.Empty;
      ListPolicyVersionsResponse reponseVersions =
        await iamClient.ListPolicyVersionsAsync(new ListPolicyVersionsRequest{
          PolicyArn = policyArn});

      // Find the default version
      foreach(PolicyVersion version in reponseVersions.Versions)
      {
        if(version.IsDefaultVersion)
        {
          defaultVersion = version.VersionId;
          break;
        }
      }

      return defaultVersion;
    }
```

## Visualizza il documento relativo alla policy
<a name="iam-policies-display-doc"></a>

Il seguente frammento mostra il documento di policy in JSON della policy IAM specificata.

L'esempio [alla fine di questo argomento mostra questo](#iam-policies-display-complete-code) frammento in uso.

```
    //
    // Method to retrieve and display the policy document of an IAM policy
    private static async Task ShowPolicyDocument(
      IAmazonIdentityManagementService iamClient, string policyArn, string defaultVersion)
    {
      // Retrieve the policy document of the default version
      GetPolicyVersionResponse responsePolicy =
        await iamClient.GetPolicyVersionAsync(new GetPolicyVersionRequest{
          PolicyArn = policyArn,
          VersionId = defaultVersion});

      // Display the policy document (in JSON)
      Console.WriteLine($"Version {defaultVersion} of the policy (in JSON format):");
      Console.WriteLine(
        $"{HttpUtility.UrlDecode(responsePolicy.PolicyVersion.Document)}");
    }
```

## Codice completo
<a name="iam-policies-display-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c19c23c19b5b1"></a>

NuGet pacchetti:
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

Elementi di programmazione:
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAM.html)

  Classe [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TIAMServiceClient.html)
+ [Namespace Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAMModel.html).Modello

  Classe [GetPolicyVersionRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TGetPolicyVersionRequest.html)

  Classe [GetPolicyVersionResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TGetPolicyVersionResponse.html)

  Classe [ListPolicyVersionsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TListPolicyVersionsRequest.html)

  Classe [ListPolicyVersionsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TListPolicyVersionsResponse.html)

  Classe [PolicyVersion](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TPolicyVersion.html)

### Il codice
<a name="w2aac19c15c19c23c19b7b1"></a>

```
using System;
using System.Web;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace IamDisplayPolicyJson
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      if(args.Length != 1)
      {
        Console.WriteLine("\nUsage: IamDisplayPolicyJson policy-arn");
        Console.WriteLine("   policy-arn: The ARN of the policy to retrieve.");
        return;
      }
      if(!args[0].StartsWith("arn:"))
      {
        Console.WriteLine("\nCould not find policy ARN in the command-line arguments:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create an IAM service client
      var iamClient = new AmazonIdentityManagementServiceClient();

      // Retrieve and display the policy document of the given policy
      string defaultVersion = await GetDefaultVersion(iamClient, args[0]);
      if(string.IsNullOrEmpty(defaultVersion))
        Console.WriteLine($"Could not find the default version for policy {args[0]}.");
      else
        await ShowPolicyDocument(iamClient, args[0], defaultVersion);
    }


    //
    // Method to determine the default version of an IAM policy
    // Returns a string with the version
    private static async Task<string> GetDefaultVersion(
      IAmazonIdentityManagementService iamClient, string policyArn)
    {
      // Retrieve all the versions of this policy
      string defaultVersion = string.Empty;
      ListPolicyVersionsResponse reponseVersions =
        await iamClient.ListPolicyVersionsAsync(new ListPolicyVersionsRequest{
          PolicyArn = policyArn});

      // Find the default version
      foreach(PolicyVersion version in reponseVersions.Versions)
      {
        if(version.IsDefaultVersion)
        {
          defaultVersion = version.VersionId;
          break;
        }
      }

      return defaultVersion;
    }


    //
    // Method to retrieve and display the policy document of an IAM policy
    private static async Task ShowPolicyDocument(
      IAmazonIdentityManagementService iamClient, string policyArn, string defaultVersion)
    {
      // Retrieve the policy document of the default version
      GetPolicyVersionResponse responsePolicy =
        await iamClient.GetPolicyVersionAsync(new GetPolicyVersionRequest{
          PolicyArn = policyArn,
          VersionId = defaultVersion});

      // Display the policy document (in JSON)
      Console.WriteLine($"Version {defaultVersion} of the policy (in JSON format):");
      Console.WriteLine(
        $"{HttpUtility.UrlDecode(responsePolicy.PolicyVersion.Document)}");
    }
  }
}
```

# Concessione dell'accesso utilizzando un ruolo IAM
<a name="net-dg-hosm"></a>

Questo tutorial mostra come utilizzare per AWS SDK per .NET abilitare i ruoli IAM sulle istanze Amazon EC2.

## Panoramica di
<a name="hosm-overview"></a>

Tutte le richieste AWS devono essere firmate crittograficamente utilizzando credenziali emesse da. AWS Pertanto, è necessaria una strategia per gestire le credenziali per le applicazioni eseguite su istanze Amazon EC2. È necessario distribuire, archiviare e ruotare queste credenziali in modo sicuro, ma anche mantenerle accessibili alle applicazioni.

Con i ruoli IAM, puoi gestire efficacemente queste credenziali. Crei un ruolo IAM e lo configuri con le autorizzazioni richieste da un'applicazione, quindi colleghi quel ruolo a un'istanza EC2. Per ulteriori informazioni sui vantaggi dell'utilizzo dei ruoli IAM, consulta [Ruoli IAM per Amazon EC2 nella Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) [User Guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Consulta anche le informazioni sui [ruoli IAM nella Guida](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) per l'utente IAM.

Per un'applicazione creata utilizzando AWS SDK per .NET, quando l'applicazione costruisce un oggetto client per un AWS servizio, l'oggetto cerca le credenziali da diverse fonti potenziali. L'ordine in cui esegue la ricerca è mostrato in. [Risoluzione di credenziali e profili](creds-assign.md)

Se l'oggetto client non trova credenziali da nessun'altra fonte, recupera credenziali temporanee con le stesse autorizzazioni di quelle che sono state configurate nel ruolo IAM e che si trovano nei metadati dell'istanza EC2. Queste credenziali vengono utilizzate per effettuare chiamate dall'oggetto client. AWS 

## Informazioni sul tutorial
<a name="about-hosm-tutorial"></a>

Seguendo questo tutorial, usi AWS SDK per .NET (e altri strumenti) per avviare un'istanza Amazon EC2 con un ruolo IAM associato, quindi vedi un'applicazione sull'istanza che utilizza le autorizzazioni del ruolo IAM.

**Topics**
+ [Panoramica di](#hosm-overview)
+ [Informazioni sul tutorial](#about-hosm-tutorial)
+ [Crea un'applicazione Amazon S3 di esempio](#net-dg-hosm-sample-s3-app)
+ [Creazione di un ruolo IAM](#net-dg-hosm-create-the-role)
+ [Avvia un'istanza EC2 e associa il ruolo IAM](#net-dg-hosm-launch-ec2-instance)
+ [Connect all'istanza EC2](#net-dg-hosm-connect)
+ [Esegui l'applicazione di esempio sull'istanza EC2](#net-dg-hosm-run-the-app)
+ [Eliminazione](#net-dg-hosm-cleanup)

## Crea un'applicazione Amazon S3 di esempio
<a name="net-dg-hosm-sample-s3-app"></a>

Questa applicazione di esempio recupera un oggetto da Amazon S3. Per eseguire l'applicazione, è necessario quanto segue:
+ Un bucket Amazon S3 che contiene un file di testo.
+ AWS credenziali sulla tua macchina di sviluppo che ti consentono di accedere al bucket.

Per informazioni sulla creazione di un bucket Amazon S3 e sul caricamento di un oggetto, consulta la [Amazon Simple Storage](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) Service User Guide. Per informazioni sulle AWS credenziali, consulta. [Configura l'autenticazione SDK con AWS](creds-idc.md)

Creare un progetto.NET Core con il codice seguente. Quindi prova l'applicazione sulla tua macchina di sviluppo.

**Nota**  
Sul computer di sviluppo è installato il.NET Core Runtime, che consente di eseguire l'applicazione senza pubblicarla. Quando crei un'istanza EC2 più avanti in questo tutorial, puoi scegliere di installare .NET Core Runtime sull'istanza. Questo ti offre un'esperienza simile e un trasferimento di file più piccolo.  
 Tuttavia, puoi anche scegliere di non installare il.NET Core Runtime sull'istanza. Se scegli questa linea d'azione, devi pubblicare l'applicazione in modo che tutte le dipendenze siano incluse quando la trasferisci sull'istanza.

### Riferimenti SDK
<a name="w2aac19c15c19c25c17c13b1"></a>

NuGet pacchetti:
+ [AWSSDKS.3](https://www.nuget.org/packages/AWSSDK.S3)

Elementi di programmazione:
+ [Spazio dei nomi Amazon.S3](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3.html)

  Classe [AmazonS3Client](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TS3Client.html)
+ Spazio dei nomi [Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3Model.html)

  Classe [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectResponse.html)

### Il codice
<a name="w2aac19c15c19c25c17c15b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;

namespace S3GetTextItem
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to retrieve a text file from an S3 bucket and write it to a local file
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string bucket =
        CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name");
      string item =
        CommandLine.GetArgument(parsedArgs, null, "-t", "--text-object");
      string outFile =
        CommandLine.GetArgument(parsedArgs, null, "-o", "--output-filename");
      if(   string.IsNullOrEmpty(bucket)
         || string.IsNullOrEmpty(item)
         || string.IsNullOrEmpty(outFile))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the S3 client object and get the file object from the bucket.
      var response = await GetObject(new AmazonS3Client(), bucket, item);

      // Write the contents of the file object to the given output file.
      var reader = new StreamReader(response.ResponseStream);
      string contents = reader.ReadToEnd();
      using (var s = new FileStream(outFile, FileMode.Create))
      using (var writer = new StreamWriter(s))
        writer.WriteLine(contents);
    }


    //
    // Method to get an object from an S3 bucket.
    private static async Task<GetObjectResponse> GetObject(
      IAmazonS3 s3Client, string bucket, string item)
    {
        Console.WriteLine($"Retrieving {item} from bucket {bucket}.");
        return await s3Client.GetObjectAsync(bucket, item);
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: S3GetTextItem -b <bucket-name> -t <text-object> -o <output-filename>" +
        "\n  -b, --bucket-name: The name of the S3 bucket." +
        "\n  -t, --text-object: The name of the text object in the bucket." +
        "\n  -o, --output-filename: The name of the file to write the text to.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

Se lo desideri, puoi rimuovere temporaneamente le credenziali che usi sulla tua macchina di sviluppo per vedere come risponde l'applicazione. (Ma assicuratevi di ripristinare le credenziali quando avete finito.)

## Creazione di un ruolo IAM
<a name="net-dg-hosm-create-the-role"></a>

Crea un ruolo IAM con le autorizzazioni appropriate per accedere ad Amazon S3.

1. Apri la [console IAM](https://console.aws.amazon.com/iam/).

1. Nel riquadro di navigazione, scegli **Ruoli**, quindi scegli **Crea** ruolo.

1. Seleziona **AWS servizio**, trova e scegli **EC2**, quindi scegli **Avanti: Autorizzazioni**.

1. **In **Allega politiche di autorizzazione**, trova e seleziona AmazonS3. ReadOnlyAccess** **Se lo desideri, esamina la politica, quindi scegli Avanti: tag.**

1. Aggiungi i tag se lo desideri, quindi scegli **Avanti: revisione**.

1. Digita un nome e una descrizione per il ruolo e quindi scegli **Create role** (Crea ruolo). Ricorda questo nome perché sarà necessario all'avvio dell'istanza EC2.

## Avvia un'istanza EC2 e associa il ruolo IAM
<a name="net-dg-hosm-launch-ec2-instance"></a>

Avvia un'istanza EC2 con il ruolo IAM creato in precedenza. Puoi farlo nei seguenti modi.
+ **Utilizzo della console EC2**

  Per avviare un'istanza utilizzando la console EC2, consulta [Launch an instance using the new launch instance wizard](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

  Mentre consulti la pagina di lancio, dovresti almeno espandere il riquadro dei **dettagli avanzati** in modo da poter specificare il ruolo IAM che hai creato in precedenza nel profilo dell'istanza **IAM**.
+ **Utilizzando il AWS SDK per .NET**

  Per informazioni su questo argomento[Avvio di un'istanza Amazon EC2](run-instance.md), vedere, [Ulteriori considerazioni](run-instance.md#run-instance-additional) inclusa la fine dell'argomento.

Per avviare un'istanza EC2 a cui è associato un ruolo IAM, la configurazione di un utente IAM deve includere determinate autorizzazioni. Per ulteriori informazioni sulle autorizzazioni richieste, consulta [Concedere l'autorizzazione a un utente per passare un ruolo IAM a un'istanza](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

## Connect all'istanza EC2
<a name="net-dg-hosm-connect"></a>

Connect all'istanza EC2 in modo da poter trasferire l'applicazione di esempio su di essa e quindi eseguire l'applicazione. Avrai bisogno del file che contiene la parte privata della key pair che hai usato per avviare l'istanza, ovvero il file PEM.

Per informazioni sulla connessione a un'istanza, consulta [Connect to your Linux](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) o [Connect to your Windows](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html) nella [Amazon EC2 User](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) Guide. Quando ti connetti, fallo in modo da poter trasferire i file dalla macchina di sviluppo all'istanza.

Se usi Visual Studio su Windows, puoi anche connetterti all'istanza utilizzando Toolkit for Visual Studio. Per ulteriori informazioni, consulta [Connessione a un'istanza Amazon EC2 nella Guida](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/tkv-ec2-ami.html#connect-ec2) per l' AWS Toolkit for Visual Studio utente.

## Esegui l'applicazione di esempio sull'istanza EC2
<a name="net-dg-hosm-run-the-app"></a>

1. Copia i file dell'applicazione dall'unità locale all'istanza.

   I file da trasferire dipendono da come è stata creata l'applicazione e dal fatto che nell'istanza sia installato o meno il.NET Core Runtime. Per informazioni su come trasferire file sulla tua istanza, consulta [Connect to your Linux](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) (vedi la sottosezione appropriata) o [Transfer files to Windows](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instanceWindowsFileTransfer.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

1. Avvia l'applicazione e verifica che funzioni con gli stessi risultati della macchina di sviluppo.

1. Verifica che l'applicazione utilizzi le credenziali fornite dal ruolo IAM.

   1. Aprire la [console di Amazon EC2](https://console.aws.amazon.com/ec2/).

   1. Seleziona l'istanza e scollega il ruolo IAM tramite **Actions**, **Instance Settings**, **Attach/Replace** IAM Role.

   1. Esegui nuovamente l'applicazione e verifica che restituisca un errore di autorizzazione.

## Eliminazione
<a name="net-dg-hosm-cleanup"></a>

Quando hai finito con questo tutorial e se non desideri più l'istanza EC2 che hai creato, assicurati di terminare l'istanza per evitare costi indesiderati. Puoi farlo nella [console Amazon EC2](https://console.aws.amazon.com/ec2/) o a livello di codice, come descritto in. [Terminazione di un'istanza Amazon EC2](terminate-instance.md) Se lo desideri, puoi anche eliminare altre risorse che hai creato per questo tutorial. Queste potrebbero includere un ruolo IAM, una coppia di chiavi EC2 e un file PEM, un gruppo di sicurezza, ecc.