C# HttpListener的CORS访问

C# HttpListener的CORS访问,c#,cors,httplistener,C#,Cors,Httplistener,我有一个C#console应用程序,运行一个HttpListener,我的客户因为CORS而被拒绝 如何使用我的设置将Access Allow Origins设置为* listener = new HttpListener(); listener.Prefixes.Add("http://+:80/"); listener.Start(); public static void ListenerCallback(IAsyncResult result) { Ht

我有一个C#console应用程序,运行一个
HttpListener
,我的客户因为CORS而被拒绝

如何使用我的设置将
Access Allow Origins
设置为
*

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

一种简单的方法是在ajax调用中使用JSONP,如下所示:

 $.support.cors = true;
    $.ajax({
        type: "POST",
        crossdomain: true,
        contentType: "application/json; charset=utf-8",
        url: ServiceURL,
        dataType: "jsonp",
        data: { Param1 : 'Test'},
        success: function (data) {
        }
您的处理程序将如下所示:

 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);
        }
上面的代码正在将响应转换为JSONP。
回调参数由ajax调用自动添加,并应返回到客户端

根据我在IIS中看到的一些其他CORS操作返回的选项响应,以下内容对我使用
HttpListener
有效。这些值可能并不完全适合您,但应该会让您朝着正确的方向前进

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

@AlexeiLevenkov添加了代码您的代码似乎试图在选项上设置两次标题,并可能为选项做更多的工作。。。我会使用Fiddler并观察服务器的响应是否合理。。。还要检查浏览器是否在调试控制台中显示任何内容……JSONP实际上是一种更简单的方法,但这个公认的答案并没有回答所提出的问题。首选答案应该描述如何允许HttpListener以允许CORS的方式响应。