我自己进行了一些测试,直接使用XmlHttpRequest
访问我的项目中的处理程序。我使用的设置是将应用程序发布在我的本地IIS上(版本为6.1,因此可能与7.5的行为有所不同),并且让Default.aspx
页面调用在Visual Studio中运行的处理程序。就像这样:
http://mymachine/WebTest/Default.aspx
-> XmlHttpRequest get request to
http://localhost:58025/WebTest/TestHandler.ashx
在处理程序中的代码:
public void ProcessRequest (HttpContext context) {
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine");
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World " + DateTime.Now.ToString());
}
使用IE9,无论我是否从处理程序发送了
Access-Control-Allow-Origin
头,行为都是相同的。IE9会发出警告,要求用户确认是否应加载内容。
Chrome(版本21.0.1180.79 m)和FF(版本14.0.1)实际上生成请求到处理程序并尊重处理程序发送回来的头信息。
因此,这在Chrome和FF中可以正常工作:
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine")
这就是所发生的事情:
context.Response.AppendHeader("Access-Control-Allow-Origin", "*")
但是我无法让它们两个在同一响应中显示多个不同的允许来源。对我来说,这些都没有起作用:
Add several response headers
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine");
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://someothermachine");
Add one header, two origins comma separated
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine, http://someothermachine");
Add one header, two origins space separated
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine http://someothermachine")
Add one header, two origins space separated
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine
为了让它工作,我按照
这个答案中提供的建议进行操作。我的处理程序看起来像这样:
public void ProcessRequest(HttpContext context)
{
string[] allowedOrigins = new string[] { "http://mymachine", "http://someothermachine" };
string origin = context.Request.Headers.Get("Origin");
if (allowedOrigins.Contains(origin))
context.Response.AppendHeader("Access-Control-Allow-Origin", origin);
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World " + DateTime.Now.ToString());
}
通过这样做,Chrome和FF都能接受来自两个来源的处理程序输出。