Skip to content

The Mechanic: Manual HTTP Server

🏗️ The Mechanic: Manual HTTP Server

Before we use ASP.NET Core and its powerful Middleware pipeline, we must understand how a web server actually works. At its core, a web server is just a program that listens on a port and parses strings.

1. The Core Component: HttpListener

The HttpListener class provides a simple way to create a web server without the overhead of the full ASP.NET Core stack.

🛠️ Lab: The 10-Line Web Server

In this lab, we will build a server that returns “Hello from Vanilla C#!” to any browser.

using System.Net;
using System.Text;

var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:5000/");
listener.Start();

Console.WriteLine("Listening on http://localhost:5000/...");

while (true) {
    var context = await listener.GetContextAsync(); // The Socket waits here
    var response = context.Response;
    
    string responseString = "<html><body><h1>Hello from Vanilla C#!</h1></body></html>";
    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
    
    response.ContentLength64 = buffer.Length;
    using var output = response.OutputStream;
    await output.WriteAsync(buffer, 0, buffer.Length);
}

2. Why Learn This?

  • The Context Object: You see the raw HttpContext (Request/Response) before it is abstracted by Controllers.
  • Routing Mechanics: You realize that “Routing” is just a series of if statements checking the context.Request.Url.
  • Performance: You understand the overhead of every layer of middleware you add.

🧪 Professor’s Challenge: The Manual Router

Task: Modify the server above to support basic routing.

  1. If the URL is /api/time, return the current time as JSON.
  2. If the URL is /api/echo?text=hello, return the text “hello”.
  3. If the URL is not found, return a 404 Not Found status code.