我的 global.asax.cs 中有以下代码,用于为某些域启用跨域 AJAX 请求:
protected void Application_BeginRequest(object sender, EventArgs e)
{
string whiteList =
System.Configuration.ConfigurationManager.AppSettings["AjaxCrossDomainWhitelist"];
if (!string.IsNullOrWhiteSpace(whiteList))
{
string[] whiteListDomains = whiteList.Split(';');
string origin = Request.Headers["origin"];
if (!string.IsNullOrEmpty(origin))
{
origin = origin.ToLower();
foreach (string domain in whiteListDomains)
{
if (domain.ToLower() == origin)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", domain);
break;
}
}
}
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
//Access Control policy has a lifetime of one hour
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "3600");
HttpContext.Current.Response.End();
}
}
}
当网站上调用的 Web 服务之一成功返回时,“Access-Control-Allow-Origin”标头将成功发送,一切正常。但是,当服务调用导致异常时;“Access-Control-Allow-Origin”标头仍添加到 HttpContext.Response;我通过捕获 Application_EndRequest 并检查 Response.Headers 集合确认了这一点。但是,当我在 Firebug、Chrome 开发工具或 Charles 中检查发送的响应时,没有发送“Access-Control-Allow-Origin”标头,我不知道为什么。
任何指针?