CORS access for HttpListener

user773737 picture user773737 · Aug 22, 2014 · Viewed 8.6k times · Source

I have a C# console app, running an HttpListener, and my clients are getting denied because of CORS.

How do I set Access-Allow-All-Origins to * with my setup?

listener = new HttpListener();
listener.Prefixes.Add("http://+:80/");
listener.Start();

    public static void ListenerCallback(IAsyncResult result)
    {
        HttpListenerContext context = Program.listener.EndGetContext(result);
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;
        if (request.HttpMethod == "OPTIONS")
        {
            response.AddHeader("Access-Control-Allow-Headers", "*");
        }
        response.AppendHeader("Access-Control-Allow-Origin", "*");
        System.IO.Stream stream = new System.IO.MemoryStream();
        request.InputStream.CopyTo(stream);
        stream.Position = 0;
        NameValueCollection coll = request.QueryString;

        if (String.IsNullOrEmpty(coll["name"]) || String.IsNullOrEmpty(coll["ext"]))
        {
            response.StatusCode = 400;
            response.ContentType = "text/html";
            using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
                writer.WriteLine("Missing parameters in queryString. Send 'name' and 'ext'");
            response.Close();
        }
        else
        {
            Program.nameResDictionary.Add(coll["name"] + "." + coll["ext"], response);
            using (var outp = File.OpenWrite(Path.Combine(Program.inDir,coll["name"] + "." + coll["ext"])))
            {
                stream.CopyTo(outp);
            }

            toLog.Add("File " + coll["name"] + "." + coll["ext"] + " added");
        }
        stream.Close();
        request.InputStream.Close();
        listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
    }

Answer

reads0520 picture reads0520 · Jan 29, 2015

Based on the OPTIONS responses I saw coming back from some other CORS stuff we're doing in IIS, the following worked for me with HttpListener. These values may not be exactly right for you, but should get you going in the right direction.

if (request.HttpMethod == "OPTIONS")
{
    response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
    response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
    response.AddHeader("Access-Control-Max-Age", "1728000");
}
response.AppendHeader("Access-Control-Allow-Origin", "*");