create a http server with a options route in csharp

Here is an example of how to create an HTTP server in C# using the HttpListener class with an OPTIONS route:

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/");
        listener.Start();

        Console.WriteLine("Server is listening on http://localhost:8080/");

        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            string httpMethod = context.Request.HttpMethod.ToUpper();

            if (httpMethod.Equals("OPTIONS"))
            {
                context.Response.AppendHeader("Allow", "GET, POST, PUT, DELETE, OPTIONS");
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.Close();
            }
            else
            {
                byte[] buffer = Encoding.UTF8.GetBytes("Hello, World!");
                context.Response.ContentLength64 = buffer.Length;
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                context.Response.OutputStream.Close();
            }
        }
    }
}
1107 chars
36 lines

This server listens on http://localhost:8080/ and responds with "Hello, World!" for all HTTP methods except for OPTIONS. When an OPTIONS request is received, it appends an Allow header with a list of allowed HTTP methods and responds with a 200 OK status code.

related categories

gistlibby LogSnag