Cross Domain Calls For WCF

A cross-domain call happens when a web page uses Javascript to access resources at a different URL which can be another domain. You will get the following error when you try access the WCF services whic is hosted in a different doamin from a jQuery ajax method.

NetworkError: 405 Method Not Allowed – http://sommedomain.com/service.svc/restService/GetMessage

The problem occurs because the browser only trusts calls from the exact same domain, unless the server says that it trusts your domain.
When the browser detects a cross-domain call, it behaves differently if your service is configured correctly. If you were expecting your JavaScript code to POST to a REST URL, that no longer happens, at least initially. Instead of performing the POST, the browser actually sends an OPTIONS verb call to your REST URL. This is called a preflight request. Your service needs to respond to the preflight request containing the OPTIONS verb and let the browser know which parameters are acceptable on a cross-site call. If everything matches up and your client is in an allowed domain, then the browser performs the original POST that you expected and everything continues on normally.

We can achieve above by writing the following piece of code in global.asax file inside Application BeginRequest event

protected void Application_BeginRequest(object sender, EventArgs e)
 
{
 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , ”*”);
 
     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" );
 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );
 
        
 
     HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" );
 
     HttpContext.Current.Response.End();
 
     }
 
}
150 150 Burnignorance | Where Minds Meet And Sparks Fly!