create a http server and read the request body as text in csharp

To create an HTTP server and read the request body in C#, you will need to use the System.Net and System.IO namespaces.

Here is a basic example that creates an HTTP server and reads the request body as text:

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

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

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

            if (request.HasEntityBody) {
                StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8);
                string requestBody = reader.ReadToEnd();

                Console.WriteLine($"Received request body: {requestBody}");
            }

            HttpListenerResponse response = context.Response;

            byte[] buffer = Encoding.UTF8.GetBytes("OK");
            response.ContentLength64 = buffer.Length;
            response.OutputStream.Write(buffer, 0, buffer.Length);

            response.Close();
        }
    }
}
1023 chars
34 lines

This code creates an HttpListener instance, adds a prefix to listen on, and starts listening for requests. It then enters a loop to handle incoming requests.

When a request is received, the code checks if it has an entity body (i.e., if it's a POST request with a request body). If it does, it reads the request body as text using a StreamReader.

After reading the request body, the code writes a response back to the client and closes the response.

gistlibby LogSnag