I did my own testing myself, using XmlHttpRequest
to access the handler in my project. The setup I used was to publish the application on my local IIS (this is version 6.1, so there may be differences in behavior up to 7.5) and so that the Default.aspx
page Default.aspx
my handler, which runs on the development server in Visual Studio. Like this:
http://mymachine/WebTest/Default.aspx -> XmlHttpRequest get request to http://localhost:58025/WebTest/TestHandler.ashx
Code in the handler:
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()); }
Using IE9, the behavior was the same regardless of whether I sent the Access-Control-Allow-Origin
header from the handler or not. IE9 gives a warning, asking the user to confirm the loading of the content.
Both Chrome (version 21.0.1180.79 m) and FF (version 14.0.1) actually generate requests to the handler and respect the header sent by the handler.
So this worked with Chrome and FF:
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine");
It happened:
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
But I couldn’t get any of them to show the content if I try to add several different allowed sources to the same answer. For me, none of them worked:
Add multiple response headers
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine"); context.Response.AppendHeader("Access-Control-Allow-Origin", "http://someothermachine");
Add one title, two sources separated by commas
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine, http://someothermachine");
Add one title, separation of two sources
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine http://someothermachine");
Add one title, separation of two sources
context.Response.AppendHeader("Access-Control-Allow-Origin", "http://mymachine; http://someothermachine");
To make it work, I had to follow the recommendations given in this answer . Then my handler looks like this:
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()); }
In this case, both Chrome and FF accept the output of the handler from both sources.