A small, explicit HTTP & WebSocket server for C#
HSB (Http Server Boxed) is a lightweight framework for APIs, real-time WebSocket, streaming and embedded servers. It doesn't hide the HTTP lifecycle: you stay close to the protocol.
$ git clone https://github.com/lorenzoconcas/HSB.git && cd HSB && dotnet build HSB.slnusing HSB;
Configuration config = new() { Port = 8080 };
config.Get("/", (Request req, Response res) =>
{
res.Send("Hello from HSB");
});
config.Get("/json", (Request req, Response res) =>
{
res.Json(new { message = "ok", timestamp = DateTime.UtcNow });
});
new Server(config).Start();
Everything a small server needs
No heavy stack, no magic. HSB gives you routing, real-time communication and hardening while keeping requests, responses, sockets and headers visible.
Two routing styles
Attribute-based controllers ([Controller], [Get], [Post]…) or Express-style minimal mappings with config.Get(...).
WebSocket
Endpoints with OnOpen, OnMessage, OnClose, async support and per-endpoint broadcast.
Streaming
Chunked responses and NDJSON with InitStream, AddStreamChunk and EndStream.
Security hardening
Opt-in security headers, request validation, per-IP rate limiting, anti-Slowloris timeouts, CORS and IP filters.
TLS & authentication
.p12 certificates, dual-port or single-port HTTPS, Bearer / Basic / API key auth with [RequireAuth].
Middleware & modules
A compiled middleware pipeline (config.Use) plus modules for interceptors, services and global hooks.
OpenAPI 3.2
Generate API documentation from attributes, including the new HTTP QUERY method (RFC 10008).
Static files
Serve a folder or embedded resources when no route matches. Great for single-page apps and dashboards.
Pick your style
Minimal endpoints for prototypes, controllers for organized APIs, WebSocket and streaming for real-time.
Express-style mappings
- Helpers for
Get,Post,Put,Delete,Patch,Head,Options,Trace,ConnectandQuery. - Resolution order: minimal mapping → controller → static files → 404.
- Perfect for small endpoints and prototypes.
config.Get("/health", (Request req, Response res) =>
{
res.Json(new { status = "ok", uptime = Environment.TickCount64 });
});
config.Post("/auth/login", (Request req, Response res) =>
{
if (!req.Body.Contains("admin"))
{
res.Json(new { error = "invalid_credentials" }, 401);
return;
}
res.Json(new { accessToken = Guid.NewGuid(), expiresIn = 3600 });
});Attribute-based controllers
- Plain C# classes: no base class to inherit.
- Route parameters with
:name, typed through[NamedParameter]. RequestandResponseinjected as parameters or fields.- Several routes per controller,
[Ws]for WebSocket.
[Controller("/users")]
public class UserController
{
private Response res = null!;
[Get("/:id")]
private void GetById([NamedParameter("id", true)] int id)
{
res.Json(new { id });
}
[Post("/")]
private void Create(Request req, Response res)
{
res.Json(new { created = true, body = req.Body });
}
}Real-time with WebSocket
- Lifecycle hooks:
OnOpen,OnMessage,OnClose,OnError. - Text and binary frames, sync and async handlers.
BroadcastandBroadcastExceptSelfper endpoint.- Hardening: allowed origins, subprotocols and per-IP connection caps.
config.WebSocket("/chat", socket =>
{
socket.OnOpen(() => socket.Broadcast("new client connected"));
socket.OnMessage(msg =>
{
// send to everyone on this route except the sender
socket.BroadcastExceptSelf(msg.Text);
});
socket.OnClose(() => socket.Broadcast("client disconnected"));
});Chunked streaming
- One JSON object per line with
application/x-ndjson. - Ideal for real-time logs, progressive exports and long-running jobs.
- The client can update UI or dashboards while the server is still working.
config.Get("/stream", async (Request req, Response res) =>
{
await res.InitStream("application/x-ndjson");
for (int i = 0; i < 10; i++)
{
var payload = JsonSerializer.Serialize(new { type = "event", index = i });
await res.AddStreamChunk(payload + "\n");
await Task.Delay(250);
}
await res.EndStream();
});Middleware, security & TLS
- Middlewares run in registration order and can short-circuit by not calling
next(). - Security options are fully opt-in: headers, validation and rate limiting.
- Native .NET TLS is the recommended path, with automatic HTTP → HTTPS upgrade.
config.Use(async (ctx, next) =>
{
ctx.Response.SetHeader("X-Trace", "hsb");
await next();
});
config.Security.Headers.Enabled = true;
config.Security.RateLimit.Enabled = true;
config.Security.RateLimit.PermitLimit = 240;
config.Security.Validation.Enabled = true;
config.SslSettings = new SslConfiguration("certificate.p12", "password")
{
PortMode = SSL_PORT_MODE.DUAL_PORT,
SslPort = 8443,
UpgradeUnsecureRequests = true
};Light, and measured
Results from the stress-test project in Experiments/StressTest (health check, JSON, large payload, slow endpoint, NDJSON streaming, WebSocket broadcast).
Indicative numbers: they depend on machine, .NET runtime, OS, payload and tooling, and are not a production throughput guarantee.
Learn more
The authored docs live in the repository. HSB is still pre-1.0: check the versions file before upgrading.