Reputation: 323
I am using a WCF service and currently it is consumed by a Silverlight application. The WCF service has clientaccesspolicy.xml and crossdomain.xml which is why there is no issue with making request from Silverlight even though the request comes from a different domain.
Now my understanding is that, adding following line of code on WCF service's web config built using .net 4.0 or above allows to make cross domain request using jsonp
<standardendpoint crossdomainscriptaccessenabled="true">
However, jsonp won't resolve my issue as I need to add custom request headers which jsonp doesn't allow as it's not really making XMLHttpRequest.
I am wondering, if I edit global.asax
of WCF service with following snippet of code, will I be able to make AJAX cross domain request successfully?
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();
}
}
Please note that I am having issue deploying the WCF project so I just wanted to know I am taking the right approach.
Upvotes: 0
Views: 922
Reputation: 323
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, Foo");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
did the trick.
In my case, I also had to add one custom header named Foo as an example as I had to pass that from client side.
Hope it helps someone!
Upvotes: 2