create a http server with a head route in csharp

To create an HTTP server with a head route in C#, we can make use of the HttpListener class provided by the System.Net namespace. Here's an example code snippet that sets up a server to listen for incoming HTTP requests and responds only to HEAD requests:

main.cs
using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/"); // Listen on localhost port 8080
        listener.Start(); // Start the listener

        Console.WriteLine("Listening...");

        while (true)
        {
            var context = listener.GetContext(); // Block until a request is received
            var request = context.Request;
            var response = context.Response;

            if (request.HttpMethod == "HEAD")
            {
                // Set the response status code (200 OK) and headers
                response.StatusCode = 200;
                response.Headers.Add("Server", "Custom-CSharp-Server");
                response.ContentType = "text/plain";
                response.Close(); // Send a response with just headers (no body)
            }
        }
    }
}
933 chars
31 lines

In this example, we create a new HttpListener instance and add a URL prefix to which we want to listen (http://localhost:8080/). Then, we start the listener and enter into an infinite loop that blocks until an incoming HTTP request is detected.

Once the request is received, we check if it's a HEAD request (request.HttpMethod == "HEAD") and if so, we modify the response headers to include a Server header, set the content type to text/plain, and set the response status code to 200.

Finally, we close the response object without writing any data to the response body, so that the server only sends back headers (no body).

Note that to test this server, you can use a tool like curl from the command line:

$ curl -I http://localhost:8080/
HTTP/1.1 200 OK
Server: Custom-CSharp-Server
Content-Type: text/plain
Date: Tue, 06 Jul 2021 18:22:01 GMT
Content-Length: 0
157 chars
7 lines

gistlibby LogSnag