create a http server and read the request body as multipart form data in csharp

To create an HTTP server in C#, you can use the built-in HttpListener class. Here is an example of how to create an HTTP server that listens for incoming requests on port 8080:

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

public class HttpServer {
    public 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;
            string method = request.HttpMethod;
            string path = request.Url.LocalPath;

            Console.WriteLine("{0} {1}", method, path);

            // Read the request body as multipart form data
            if (method == "POST") {
                MemoryStream ms = new MemoryStream();
                request.InputStream.CopyTo(ms);
                byte[] data = ms.ToArray();
                string contentType = request.ContentType;
                if (contentType.StartsWith("multipart/form-data")) {
                    MultipartFormDataParser parser = new MultipartFormDataParser(data, contentType);
                    foreach (var file in parser.Files) {
                        Console.WriteLine("Received file: {0}", file.FileName);
                        // Do something with the file
                    }
                    foreach (var field in parser.Fields) {
                        Console.WriteLine("{0}: {1}", field.Name, field.Value);
                        // Do something with the field value
                    }
                }
            }

            HttpListenerResponse response = context.Response;
            string responseString = "Hello, World!";
            byte[] responseBytes = Encoding.UTF8.GetBytes(responseString);
            response.ContentType = "text/plain";
            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength64 = responseBytes.Length;
            response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
            response.OutputStream.Close();
        }
    }
}
2055 chars
51 lines

In the example above, we are using the MultipartFormDataParser class to parse the request body as multipart form data. You can find the source code for this class on GitHub: https://github.com/nemesissoft/Nemesis.Essentials/blob/master/Nemesis.Essentials.Web/MultipartFormDataParser.cs

gistlibby LogSnag