> 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/es/plataforma/plugins/c-api-endpoints.md).

# Endpoints de la API de C\#

**Identificador:** `PowerShellUniversal.Language.CSharp`

Este plugin crea un entorno basado en C# que puede utilizarse para crear endpoints de API con código C#. Las API creadas con C# son mucho más rápidas que los endpoints basados en PowerShell. Los endpoints se ejecutan directamente en el servicio de PowerShell Universal. Cualquier excepción lanzada desde su endpoint se gestionará y se devolverá un código de estado válido al llamante.

Debe crear los endpoints con el parámetro -Path y especificar el entorno `C#` para que el endpoint funcione correctamente.

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

**Definir un endpoint**

Dentro del endpoint de C#, hay dos clases de interés. La primera es la variable `request` que se pasa al endpoint. Es un objeto `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; }
}
```

En su endpoint, puede acceder a esta variable automáticamente.

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

El endpoint debe devolver un objeto `ApiResponse`. Este objeto tiene la siguiente definición.

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

Puede devolver una respuesta creando un nuevo objeto y devolviéndolo desde su endpoint.

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

Al definir el contenido de un endpoint, tenga en cuenta que el código se añade a una clase con nombre dinámico que tiene una única función Execute. Su código debe tener una sintaxis válida para un fichero de origen de este tipo.

```csharp
using PowerShellUniversal;

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

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

Puede acceder al contenedor del servicio de PowerShell Universal dentro de su endpoint accediendo a la propiedad `ServiceProvider` en su endpoint. Actualmente no documentamos los servicios internos de PowerShell Universal.

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

### Referencias

Puede controlar qué ensamblados se referencian utilizando la palabra clave `#ref`. El valor puede ser un fichero DLL en el directorio de instalación de PowerShell Universal, o la ruta completa a otro ensamblado.

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

### Uso de espacios de nombres

Puede referenciar un espacio de nombres utilizando la palabra clave `#using`.

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

### Variables

Puede acceder a las variables en los endpoints de C# con los métodos `GetVariable`, `GetSecretString` y `GetSecretCredential`.

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

Para acceder a un `PSCredential`, puede hacer lo siguiente.

```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/es/plataforma/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.
