create a http server with a get route in csharp

main.cs
using System;
using System.IO;
using System.Net;
using System.Text;

class Server 
{
    static void Main(string[] args) 
    {
        string url = "http://localhost:8080/";
        HttpListener listener = new HttpListener();

        listener.Prefixes.Add(url);
        listener.Start();
        Console.WriteLine("Listening on {0}", url);

        while (true) 
        {
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            // Handle only GET requests
            if (request.HttpMethod == "GET") 
            {
                Console.WriteLine("{0} request received.", request.HttpMethod);
                string responseString = "Hello, World!";
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
        }
    }
}
1104 chars
37 lines

In the above code, we first define a url for our server which listens on http://localhost:8080/. We then create an HttpListener object and add the prefix to the listener using listener.Prefixes.Add(url).

After starting the listener using listener.Start(), we enter into an infinite loop to keep listening for incoming HTTP requests.

For each incoming request, we use listener.GetContext() to get the context of the request which contains both the HttpListenerRequest and HttpListenerResponse objects.

We then check if the request is a GET request using if (request.HttpMethod == "GET") and prepare our response accordingly. In this case, we set the response content to "Hello, World!" and send it back to the client.

Finally, we close the output stream using output.Close().

related categories

gistlibby LogSnag