Fixing a WCF Web Service for Cross Domain/Browser Support

I had an issue recently where I was attempting to make my CRM 2011 customisations cross browser compatible. The issue was when I was calling a Web Service via Jquery’s AJAX methods. It was working fine in Internet Explorer, but when I was trying to access it from a Web Resource within Chrome, I was getting an issue that was suggesting it was a cross domain problem.

Although the web service was running on the same host, as it was on a different port, it was being classed as a cross domain ajax call and Chrome was stopping it.

I spent a while trying to find out how to fix the client JavaScript assuming the issue was how I was calling it, and then I stumbled on some useful information about Web Services and a nice little piece of code to enable the web service to work perfectly, leaving the client alone.

The issue boiled down to some extra calls being made to gather OPTIONS around the safety of the request.

“OPTIONS” Request called as “Preflight Request” – “preflighted” requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send and this request expects appropriate headers saying that service is allowing to access the service as a Response

The fix is to add a global.asax file to the web service project and include the following code which handles this OPTIONS request. Build, and deploy and all of a sudden it was working fine in Chrome as well 🙂

protected void Application_BeginRequest(object sender, EventArgs e)
{          
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");          
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {               
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        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();              
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.