create a http server and parse cookies in csharp

To create an HTTP server in C#, you can use the HttpListener class from System.Net namespace. To parse cookies in the HTTP request, you can use the Cookies property of the HttpListenerRequest class.

Here's an example code snippet that creates an HTTP server and parses cookies in C#:

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

class HttpServer
{
    static void Main(string[] args)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/"); // listen on localhost port 8080
        listener.Start();

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

            // parse cookies
            if (request.Cookies.Count > 0)
            {
                foreach (Cookie cookie in request.Cookies)
                {
                    Console.WriteLine($"{cookie.Name}={cookie.Value}");
                }
            }

            // return a response
            HttpListenerResponse response = context.Response;
            string responseString = "<html><body><h1>Hello, World!</h1></body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.OutputStream.Close();
        }
    }
}
1139 chars
37 lines

This code creates an HttpListener on port 8080 of localhost. It then listens for incoming HTTP requests, and for each request, it parses the cookies using the Cookies property of the HttpListenerRequest class. Finally, it returns a simple HTML response.

Note that running an HTTP server on your local machine may require administrative privileges, and you may need to add a firewall exception for the port you are listening on.

gistlibby LogSnag