user773737
user773737

Reputation:

CORS access for HttpListener

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);
    }

Upvotes: 9

Views: 13710

Answers (2)

reads0520
reads0520

Reputation: 716

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", "*");

Upvotes: 17

Sam
Sam

Reputation: 789

A simple approach would be to use JSONP in your ajax calls as below :

 $.support.cors = true;
    $.ajax({
        type: "POST",
        crossdomain: true,
        contentType: "application/json; charset=utf-8",
        url: ServiceURL,
        dataType: "jsonp",
        data: { Param1 : 'Test'},
        success: function (data) {
        }

and your handler will look like this :

 public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string callback = context.Request.QueryString["callback"];
            string Param1 = context.Request.QueryString["Param1"];
            object dataToSend = null;
            JavaScriptSerializer js = new JavaScriptSerializer();
            string JSONstring = js.Serialize(dataToSend);
            string JSONPstring = string.Format("{0}({1});", callback, JSONstring);
            context.Response.Write(JSONPstring);
        }

the above code is converting the response to JSONP. the callback parameter is automatically added by the ajax call and should be returned to the client

Upvotes: 1

Related Questions