create a http server with a put route in csharp

To create an HTTP server with a PUT route in C#, you can use the HttpListener class. Here's an example:

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

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

        while (true)
        {
            var context = listener.GetContext();
            if (context.Request.HttpMethod == "PUT")
            {
                using (var reader = new StreamReader(context.Request.InputStream))
                {
                    var body = reader.ReadToEnd();
                    Console.WriteLine($"Received PUT request with body: {body}");
                }
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
            else
            {
                context.Response.StatusCode = 405;
                context.Response.Close();
            }
        }
    }
}
943 chars
35 lines

This server listens on port 8080 for incoming requests. When it receives a PUT request, it reads the body of the request and prints it to the console. It then responds with a 200 status code. If it receives any other type of request, it responds with a 405 status code.

Note that this is a very basic example and does not include error handling, authentication, or other features you would typically need in a real-world application.

gistlibby LogSnag