CORS access for HttpListener
本文关键字:HttpListener for access CORS | 更新日期: 2023-09-27 18:18:59
我有一个c#控制台应用程序,运行HttpListener
,我的客户端因为CORS而被拒绝。
如何将Access-Allow-All-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);
}
根据OPTIONS响应,我看到我们在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", "*");
一种简单的方法是在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调用自动添加,并应返回给客户端