create a http server and upload a file and return a json response in csharp

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

class HttpServer {
    public static void Main(string[] args) {
        HttpListener httpListener = new HttpListener();
        httpListener.Prefixes.Add("http://localhost:8000/");
        httpListener.Start();

        Console.WriteLine("Server started");

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

            if (context.Request.HttpMethod == "POST" && context.Request.RawUrl == "/upload") {
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;

                // Get file name from the headers
                string fileName = request.Headers["X-File-Name"];

                // Create stream to write the file
                var filePath = Path.Combine(Path.GetTempPath(), fileName);
                using (var writer = new FileStream(filePath, FileMode.Create)) {
                    request.InputStream.CopyTo(writer);
                }

                // Return JSON response with file name and size
                var fileInfo = new FileInfo(filePath);
                var jsonResponse = JsonConvert.SerializeObject(new {
                    fileName = fileInfo.Name,
                    size = fileInfo.Length
                });

                byte[] buffer = Encoding.UTF8.GetBytes(jsonResponse);

                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);

                response.Close();
            }
        }
    }
}
1632 chars
48 lines

This is a simple HTTP server that listens on port 8000 on "localhost" and accepts POST requests to "/upload" to upload a file. The file is saved to the system's temporary folder and a JSON response is returned with the file name and size. The response is serialized using Newtonsoft.Json.

gistlibby LogSnag