AvalonFlow 1.0.3

dotnet add package AvalonFlow --version 1.0.3
                    
NuGet\Install-Package AvalonFlow -Version 1.0.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AvalonFlow" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AvalonFlow" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="AvalonFlow" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AvalonFlow --version 1.0.3
                    
#r "nuget: AvalonFlow, 1.0.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AvalonFlow@1.0.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AvalonFlow&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=AvalonFlow&version=1.0.3
                    
Install as a Cake Tool

AvalonFlow REST API

Bienvenido a la documentación de la API REST de AvalonFlow. Este proyecto implementa un framework HTTP minimalista basado en HttpListener para construir APIs REST modernas en C#.


📚 Características

  • Ruteo mediante atributos ([HttpGet], [HttpPost], etc.).
  • Inyección de parámetros y deserialización automática.
  • Manejo de respuestas con ActionResult, FileActionResult y StreamFileActionResult.
  • Soporte para descarga y streaming de archivos.
  • Sistema de controladores tipo MVC.
  • Seguridad por token personalizada.

⚙️ Ejemplo de uso

using AvalonFlow;
using AvalonFlow.Rest;
using AvalonFlowRest.Services;

namespace AvalonFlowRest
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            // Opcional: puedes leer puerto de args o config
            int port = 5000;

            var server = new AvalonRestServer(port);
            // al iniciar el servidor
            AvalonServiceRegistry.RegisterSingleton<EmailService>(new EmailService());

            await server.StartAsync(); // Corre el servidor indefinidamente
        }
    }
}


🚀 Ejecución Rápida

# Ejecutar desde consola
$ dotnet run

El servidor correrá por defecto en:

http://localhost:5000/

📂 Endpoints

💾 Descargar Archivo

GET /api/file/download

Descarga un archivo como attachment.

GET /api/file/download HTTP/1.1

🎥 Ver Video (Streaming)

GET /api/file/video

Stream de un archivo de video.

GET /api/file/video HTTP/1.1

🖼️ Ver Imagen

GET /api/file/image

Renderiza la imagen inline.

GET /api/file/image HTTP/1.1

Se recomienda mostrarla en HTML con img y pointer-events: none para evitar interacciones.


🧭 Uso de Controllers

[AvalonController("api/[controller]")]
public class FileController : AvalonControllerBase
{
    [HttpGet("download")]
    public ActionResult DownloadFile() => ...;
}
  • [AvalonController]: Define la ruta base del controller.
  • Hereda de AvalonControllerBase para acceso a métodos como Ok(), NotFound(), File(), etc.

Métodos soportados:

  • [HttpGet("ruta")]
  • [HttpPost("ruta")]
  • [HttpPut("ruta")]
  • [HttpDelete("ruta")]
  • [HttpPatch("ruta")]
  • [HttpOptions("ruta")]

Inyección de parámetros

[HttpGet("usuario/{id}")]
public ActionResult GetUsuario(int id)
{
    // id es inyectado desde la ruta
}

[HttpPost("crear")]
public ActionResult CrearUsuario(UsuarioDto dto)
{
    // dto es deserializado automáticamente desde el body JSON
}

🔐 Seguridad y Autenticación

AvalonFlow permite validar manualmente las peticiones antes de ejecutar los controladores:

if (!context.Request.Headers.TryGetValue("Authorization", out var token) || !ValidateToken(token))
{
    await RespondWith(context, 401, new { error = "Unauthorized" });
    return;
}

También puedes aplicar autorización por controlador o endpoint:

[HttpGet("secure")]
public ActionResult GetProtectedFile()
{
    if (!HttpContext.User?.IsAuthenticated ?? true)
        return Unauthorized("Token inválido");
    // lógica segura
}

Puedes extender AvalonHttpContext para guardar info del usuario autenticado.


🛡️ Seguridad para Archivos

Para proteger el acceso a archivos y multimedia:

  • ✅ Requiere autenticación JWT o tokens temporales.
  • ✅ Evita Content-Disposition: attachment si no deseas descargas.
  • ✅ Implementa token o exp para URLs seguras.
  • ✅ Usa marcas de agua si es contenido sensible.
  • ✅ Añade headers:
context.Response.AddHeader("Cache-Control", "no-store");
context.Response.AddHeader("Pragma", "no-cache");
context.Response.AddHeader("Content-Security-Policy", "default-src 'none';");

🔧 Ejemplo de Uso

[HttpGet("image")]
public ActionResult GetImage()
{
    var path = Path.Combine(Directory.GetCurrentDirectory(), "files", "imagen.jpg");
    if (!System.IO.File.Exists(path)) return NotFound("Imagen no encontrada.");
    var stream = System.IO.File.OpenRead(path);
    return new StreamFileActionResult(stream, "image/jpeg", "imagen.jpg", isAttachment: false);
}

✨ Contribuciones

Tus contribuciones son bienvenidas. Abre un Pull Request o issue para colaborar.


📄 Licencia

Este proyecto está licenciado bajo MIT. Consulta LICENSE para más detalles.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.3 141 7/5/2025
1.0.2 318 6/10/2025
1.0.1 312 6/9/2025
1.0.0 185 6/5/2025