> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/powershell-universal/it/piattaforma/plugins/c-api-endpoints.md).

# Endpoint API C\#

**Identificatore:** `PowerShellUniversal.Language.CSharp`

Questo plugin crea un ambiente basato su C# che può essere utilizzato per creare endpoint API con codice C#. Le API create con C# sono molto più veloci degli endpoint basati su PowerShell. Gli endpoint vengono eseguiti direttamente nel servizio PowerShell Universal. Qualsiasi eccezione generata dal suo endpoint verrà gestita e un codice di stato valido verrà restituito al chiamante.

Deve creare gli endpoint con il parametro -Path e specificare l'ambiente `C#` affinché l'endpoint funzioni correttamente.

```powershell
New-PSUEndpoint -Url /csharp -Path csharp.cs -Environment 'C#'
```

**Definizione di un endpoint**

All'interno dell'endpoint C# ci sono due classi di interesse. La prima è la variabile `request` che viene passata all'endpoint. È un oggetto `ApiRequest`.

```csharp
public class ApiRequest
{
    public long Id { get; set; }
    public ICollection<KeyValue> Variables { get; set; } = new List<KeyValue>();
    public IEnumerable<ApiFile> Files { get; set; } = new List<ApiFile>();
    public string Url { get; set; }
    public ICollection<KeyValue> Headers { get; set; } = new List<KeyValue>();
    public byte[] Data { get; set; }
    public int ErrorAction { get; set; }
    public ICollection<KeyValue> Parameters { get; set; } = new List<KeyValue>();
    public string Method { get; set; }
    public ICollection<KeyValue> Cookies { get; set; } = new List<KeyValue>();
    public string ClaimsPrincipal { get; set; }
    public string ContentType { get; set; }
    public string[] Roles { get; set; }
}
```

Nel suo endpoint può accedere automaticamente a questa variabile.

```csharp
if (request.ContentType == "application/json")
{
     // Do some stuff with JSON
}
```

L'endpoint deve restituire un oggetto `ApiResponse`. Questo oggetto ha la definizione seguente.

```csharp
public class ApiResponse
{
    public int StatusCode { get; set; } = 200;
    public string Body { get; set; }
    public List<KeyValue> Cookies { get; set; } = new List<KeyValue>();
    public byte[] Data { get; set; } = Array.Empty<byte>();
    public string ContentType { get; set; } = "text/plain";
    public List<KeyValue> Headers { get; set; } = new List<KeyValue>();
    public ApiFile File { get; set; }
}
```

Può restituire una risposta creando un nuovo oggetto e restituendolo dal suo endpoint.

```csharp
return new ApiResponse {
    StatusCode = 401
};
```

Quando definisce il contenuto di un endpoint, tenga presente che il codice viene aggiunto a una classe con nome generato dinamicamente con una singola funzione Execute. Il suo codice deve avere una sintassi valida per tale file sorgente.

```csharp
using PowerShellUniversal;

public class c{id} : ExecutionClass {{ 
    public static ApiResponse Execute(ApiRequest request) 
    {{ 
        {fileContents} 

        return new ApiResponse();
    }} 
}}";
```

Può accedere al contenitore di servizi di PowerShell Universal all'interno del suo endpoint accedendo alla proprietà `ServiceProvider` nell'endpoint. Attualmente non documentiamo i servizi interni di PowerShell Universal.

```csharp
var database = ServiceProvider.GetService(typeof(IDatabase));
```

### Riferimenti

Può controllare quali assembly vengono referenziati utilizzando la parola chiave `#ref`. Il valore può essere un file DLL nella directory di installazione di PowerShell Universal oppure il percorso completo di un altro assembly.

```csharp
#ref PowerShellUniversal.Apis.dll
#ref C:\assemblies\markdiag.dll
```

### Using dei namespace

Può fare riferimento a un namespace utilizzando la parola chiave `#using`.

```csharp
#using System.Management.Automation
```

### Variabili

Può accedere alle variabili negli endpoint C# con i metodi `GetVariable`, `GetSecretString` e `GetSecretCredential`.

```csharp
return new ApiResponse {
    StatusCode = 200
    Body = GetVariable("MyVar").ToString()
};
```

Per accedere a un `PSCredential`, può procedere come segue.

```csharp
#ref System  
#ref System.Management.Automation

return new ApiResponse { 
    StatusCode = 200, 
    Body = GetSecretCredential("MyCred").UserName.ToString() 
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.devolutions.net/powershell-universal/it/piattaforma/plugins/c-api-endpoints.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
