Of CORSe, it’s easy to test

I read this informative post on CORS at the weekend, and realised that the best way to get to grips with it, is to try some experiments. I hadn’t realised before how easy this would be in C#. It’s easy to write a mini-web server that handles a single call using code like this.

            IPAddress ipAddress = IPAddress.Parse("");
            TcpListener listener = new TcpListener(ipAddress, 8182);

            using (var clt = listener.AcceptTcpClient())
            using (NetworkStream ns = clt.GetStream())
            using (StreamReader sr = new StreamReader(ns))
            using (StreamWriter sw = new StreamWriter(ns))
                var msg = sr.ReadLine();

                if (msg.StartsWith("GET"))
                    string line;
                    while ((line = sr.ReadLine()) != "")


                    sw.WriteLine("HTTP/1.1 200 OK");
                    //sw.WriteLine("Access-Control-Allow-Origin: chrome://newtab");

With that code running, you can start Chrome in Incognito mode, and then run the following code in the console.

var h = new XMLHttpRequest()
h.open("GET", "http://localhost:8182", true)

which gives the error

(index):1 Access to XMLHttpRequest at 'http://localhost:8182/' from origin 'chrome://newtab' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Uncommenting the Access Control line in the above code allows the request to succeed.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s