我正在使用 WCF 服务,目前它由 Silverlight 应用程序使用。WCF 服务具有 clientaccesspolicy.xml 和 crossdomain.xml,这就是为什么从 Silverlight 发出请求没有问题,即使请求来自不同的域。
现在我的理解是,在使用 .net 4.0 或更高版本构建的 WCF 服务的 Web 配置上添加以下代码行允许使用jsonp
<standardendpoint crossdomainscriptaccessenabled="true">
但是,jsonp 无法解决我的问题,因为我需要添加 jsonp 不允许的自定义请求标头,因为它并没有真正生成 XMLHttpRequest。
我想知道,如果我global.asax
使用以下代码片段编辑 WCF 服务,我能否成功发出 AJAX 跨域请求?
protected void Application_BeginRequest(object sender, EventArgs e)
{
EnableCrossDomainAjaxCall();
}
private void EnableCrossDomainAjaxCall()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content- Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
请注意,我在部署 WCF 项目时遇到问题,所以我只想知道我采用了正确的方法。