create a http server and read the request body as form url encoded in csharp

To create a HTTP server in C#, we can leverage the HttpListener class provided by .NET. Here's an example of how to create a simple HTTP server that listens on port 8080 and reads the request body as form-urlencoded.

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

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

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

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

            if (request.HttpMethod == "POST" && request.ContentType == "application/x-www-form-urlencoded")
            {
                using (StreamReader reader = new StreamReader(request.InputStream))
                {
                    string body = reader.ReadToEnd();
                    Console.WriteLine("Body: " + body);
                    // process the form data here
                }
            }

            HttpListenerResponse response = context.Response;
            string responseString = "Hello World!";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }
}
1281 chars
40 lines

In this example, we create an instance of HttpListener and add a prefix to indicate which URLs we want to listen on. We then start the listener and loop indefinitely, waiting for incoming requests.

When we receive a request, we check if it's a POST request with the content type application/x-www-form-urlencoded. If it is, we read the request body as a string and process the form data as needed.

After processing the request, we send a simple "Hello World!" response back to the client.

gistlibby LogSnag