create a http server with a post route in csharp

Here's an example of how to create a simple HTTP server with a POST route in C# using the built-in HttpListener class:

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

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

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

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

                if (context.Request.HttpMethod == "POST" && context.Request.Url.AbsolutePath == "/example-route")
                {
                    Console.WriteLine("Received a POST request to /example-route");

                    using (Stream body = context.Request.InputStream)
                    {
                        Encoding encoding = context.Request.ContentEncoding;
                        StreamReader reader = new StreamReader(body, encoding);
                        string requestBody = reader.ReadToEnd();
                        Console.WriteLine($"Request body: {requestBody}");
                    }

                    context.Response.StatusCode = 200;
                }
                else
                {
                    context.Response.StatusCode = 404;
                }

                context.Response.Close();
            }
        }
    }
}
1403 chars
46 lines

This code listens for requests on http://localhost:8080/ and checks if a received request is a POST request with the path /example-route. If it is, it reads the request body and logs it to the console, then responds with a 200 OK status code. If the request is something else, it responds with a 404 Not Found status code.

Note that this is a very basic example and not suitable for production use. In a real-world application, you would likely want to use a more robust framework, such as ASP.NET or NancyFX, to handle routing and request handling.

gistlibby LogSnag