Thursday, March 1, 2012

Fix WCf 405 Method Not Allowed.

I was developing a WCF application and published it under IIS 7. My service is working perfectly when calling it through a server side code. Now my client app requires me to call the service from the client side and I used JQuery for that. When I do my request using JQuery.Ajax() it gives me this error "405 Method Not Allowed".





I've been stumbling over the internet to find a solution for this problem and It took me a good 4 hours for it. I tried using different calling approach on JQuery, such as $.getJSON(), $.post and etc. I also tried to re configure my web.config but none of them works.

Luckily I found this fix to the problem.

The Fix

Add a Global.asax to your project and update Application_BeginRequest method with this snippet.. If the method does not exist don't worry, you can just paste this code to the class.

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();
              }
}