我假设您打算写ashx,而不是ascx。 ProcessRequest (HttpContext context) 方法的存在表明它是一个通用处理程序,而不是用户控件。
我制作了一个非常简单的页面来测试:
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
</head>
<body>
<div id="testCorsDiv">
</div>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "/Handler/testCors.ashx",
dataType: "text",
success: function (theData) { $("#testCorsDiv").text(theData); },
error: function (theData) { alert('error'); }
});
</script>
<% if(string.IsNullOrEmpty(Request.QueryString["sandboxed"])) { %>
<iframe src="http://127.0.0.1:49253/SandboxTest.aspx?sandboxed=true" sandbox="allow-scripts" width="600">
</iframe>
<% } %>
</body>
</html>
我在http://localhost:49253/SandboxTest.aspx 上加载页面。然后页面向http://localhost:49253/Handler/testCors.ashx 发出ajax 请求,并将其输出放入testCorsDiv div。这会为处理程序生成一个直接的GET(因为它来自同一来源)并插入输出。
页面中还有一个沙盒 iframe,它使用 URL http://127.0.0.1:49253/SandboxTest.aspx 加载相同的页面。 ?sandboxed=true 用于防止 iframe 递归加载内部 iframe。然后,在 iframe 中加载的页面将尝试向 http://127.0.0.1:49253/Handler/testCors.ashx 发出 ajax 请求,并在其自己的 testCorsDiv div 副本中显示输出。
只要沙盒 iframe 有 allow-scripts 这就像一个魅力。 iframe 生成一个如下所示的 OPTIONS 请求(来自 Fiddler,使用 Chrome 测试):
OPTIONS http://127.0.0.1:49253/Handler/testCors.ashx HTTP/1.1
Host: 127.0.0.1:49253
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: GET
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
Access-Control-Request-Headers: accept, x-requested-with
Accept: */*
Referer: http://127.0.0.1:49253/SandboxTest.aspx?sandboxed=true
Accept-Encoding: gzip, deflate, sdch
Accept-Language: fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4
我的testCors.ashx 处理程序然后吐出一些标头,说这看起来不错,然后浏览器跟进GET,它就可以工作了。
testCors.ashx 这样做:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
context.Response.AppendHeader("Access-Control-Allow-Headers", "content-type, x-requested-with, accept");
context.Response.AppendHeader("Access-Control-Allow-Methods", "POST, OPTIONS, GET");
context.Response.Write("Hello World");
}
所以我的测试表明应该可以做你想做的事。尽管这可能是一个问题,但如果您的处理程序只能由经过身份验证/授权的用户访问,那么这可能是一个问题。如您所见,OPTIONS 请求没有向处理程序发送 cookie。但另一方面,您的问题表明对您的选项请求的响应是Status Code:200。我想如果缺少所需的身份验证 cookie,那将是一些 4**。
结束,我真的不知道您的情况出了什么问题,但也许(?)我的简单示例页面可以为您提供一些线索,帮助您自己找到问题。