Http Server in C#

Here’s the translation of the HTTP server example from Go to C#:

using System;
using System.Net;
using System.IO;
using System.Collections.Generic;

class HttpServer
{
    // A fundamental concept in ASP.NET Core is middleware. Middleware is software
    // that's assembled into an app pipeline to handle requests and responses.
    // Each component chooses whether to pass the request to the next component 
    // in the pipeline, and can perform work before and after the next component
    // in the pipeline is invoked.

    static void Hello(HttpListenerContext context)
    {
        // Functions serving as handlers take a HttpListenerContext as an argument.
        // The response is used to fill in the HTTP response. Here our simple
        // response is just "hello\n".
        
        string responseString = "hello\n";
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        context.Response.ContentLength64 = buffer.Length;
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
    }

    static void Headers(HttpListenerContext context)
    {
        // This handler does something a little more sophisticated by reading
        // all the HTTP request headers and echoing them into the response body.
        
        string responseString = "";
        foreach (string key in context.Request.Headers.AllKeys)
        {
            foreach (string value in context.Request.Headers.GetValues(key))
            {
                responseString += $"{key}: {value}\n";
            }
        }
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        context.Response.ContentLength64 = buffer.Length;
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
    }

    static void Main(string[] args)
    {
        // We create a HttpListener and configure it to listen on port 8090
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8090/");
        listener.Start();
        Console.WriteLine("Listening...");

        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            
            // We handle different routes based on the request URL
            if (context.Request.Url.AbsolutePath == "/hello")
            {
                Hello(context);
            }
            else if (context.Request.Url.AbsolutePath == "/headers")
            {
                Headers(context);
            }
            
            context.Response.Close();
        }
    }
}

To run this C# HTTP server:

  1. Save the code in a file named HttpServer.cs.
  2. Compile the code:
$ csc HttpServer.cs
  1. Run the compiled executable:
$ HttpServer.exe

The server will start and listen on port 8090. You can then access it using curl or a web browser:

$ curl http://localhost:8090/hello
hello

$ curl http://localhost:8090/headers
Host: localhost:8090
User-Agent: curl/7.68.0
Accept: */*

This C# implementation uses the HttpListener class, which provides a simple, programmatically controlled HTTP protocol listener. It’s suitable for learning purposes but for production scenarios, you might want to use more robust frameworks like ASP.NET Core.

The structure of the program is similar to the original, with methods for handling different routes (Hello and Headers). The main difference is in how the server is set up and how requests are handled in an infinite loop, which is more explicit in this C# version compared to the Go version where much of this is abstracted away.