Accessing WCF from Jquery By seeing this first time we think that it is very common thing on developer life, I too started this simple task for just want to know how it works But i got good amount of Knowledge on REST,WCF,Creating Custom Behaviors for WCF Service.
Coming to the problem, I have one simple requirement i need to call WCF Service from JavaScript(Jquery).
I have one REST Enabled WCF Service hosted on IIS and My Client Application running on ASP.NET Development Server
My Jquery code to call the Service.
$.ajax({ type: "GET", dataType: "json", contentType: "application/json", url: http://localhost/Services/SampleService.svc/ADD/firstNumber/SecondNumber, success: function (msg) { alert('Result:' msg); }, error: function (errmsg) { alert('error ocured:' + errmsg.responseText); }, complete: function () { alert('completed'); } });
on Button click i am calling my service,the interesting point is am able to see the output in IE but not in Chrome and Mozilla
after watching the requests from Fiddler it shows that the call i have made is of type ‘OPTIONS’ i never heard of this before
here am making ‘GET’ call but request going like OPTIONS and the response from Service is “405 Method Not Allowed”
but the Success call back function is executed after some googling i got know this is CORS (Cross Origin Resource Sharing)call
it just CrossDomainAccess then i have added CrossDomainAccessPolicy.xml file on my service but it doesn’t work.
Finally i found one article on Mozilla Developer Network here they said any Cross-Domain(site) HTTP requests first browser will send
‘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
to achieve this we have two solutions
- WCF Custom behaviors
- Modifying the Global.asax file’s Application_BeginRequest event.
here i am giving solution for Global.asax i.e second one.
to change the ‘OPTIONS’ request with appropriate Response Headers
Add Global.asax file to the project and update Application_BeginRequest method with this snippet..
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(); } }
Thats it your client will access the WCF service from Jquery on any browser
Thanks Dude ! It’s work for me….
Your style is very unique compared to other folks I’ve read stuff from. Thank you for posting when you’ve got the opportunity,
Guess I’ll just book mark this blog.
I was pulling my hair out trying to resolve this issue. Most other solutions that I found suggested using a , but I couldn’t get that to work as “*” is not a valid method.
Your method is much cleaner as it addresses the problem directly and without having to resort to allowing all methods.
Thank you.
taken from
http://blog.weareon.net/calling-wcf-rest-service-from-jquery-causes-405-method-not-allowed/#comment-1107
modifying this line
HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Headers”, “Content-Type, Accept”);
to
HttpContext.Current.Response.AddHeader(“Access-Control-Allow-Headers”, “Content-Type, Accept, x-requested-with”);
resolves the issues with POST requests.
Hi Oliver,
Thanks for writing me, the original post also is mine i only wrote on http://blog.weareon.net
Thanks Praneeth, it worked for me, I was struggling for a whole day to get it work. Adding customHeaders in web.config did not work, when I added this code into global.asax, it was a charm. Thank you so much.
Please you can explain the first solution with WCF Custom behaviors, this is a great post, thanks for sharing
You rock man…Praneeth excellent post …Great info with accurate fix ..right on
So many thanks, you are just liberate me from hours of debugging… I own you a beer…
thanx man u save alot of the time
Dude – you saved a life.
Gracias amigo, Funciona perfectamente, ojalá hubiese leido este post unas horas antes 😀
many-many thanks to man you saved me
Thanks, this worked for us. Having the header re-written in the web.config file, threw an error “Multiple Entries”. Removed it from web.config but placed in the Global.asax file and it worked like a charm. Thanks again.
Thanks for the well-explained article. I’m just confused over something, I can’t find the “Global.asax” file in my WCF webservice projet.. Where is it located? The code you provided below has to be placed in that file or in the Service.svc.cs file ? Please answer and Thanks a lot in advance
Hi sally,
Thanks For the Comment
Please go ahead and select add NewItem and add “Global.asax” file to your project and add the event you want to handle
for the list of events in Global.asax file refer: http://aspalliance.com/1114_Understanding_the_Globalasax_file.3
This is still helping people (like me). Thanks for the tip!
Thanks this worked great!
Gracias, funcionó perfectamente!!!
Thank You!!
Wooooww… I’m really, really happy. That its my solution for 3 days of frustration.
Thanks for all.
YESSSSSSSSSSSSSSSSSSSSSSSSSSS!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Genius!!!!!!!!!!!!!!!!