I am trying to make an ajax GET request to a WCF web service method through javascript. The request returns with a 400 \"Bad Request\" error everytime. But if I invoke the s
I see that the biggest difference between the WCF test client request and my ajax request is that I make a GET request and pass in the name of the web service method in the url while the WCF test client makes a post request and sends in the web service method name in a SOAP envelope.
Seems that your service is configured with SOAP binding and cannot work with AJAX Get requests.
You need to use WebHttpBinding
if you want to consume your service from JS.
[WebGet]
attribute got your operation binding="webHttpBinding"
There are many samples in internet. For example this one http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
You need to add service section to your web.config file. Host does not know that you want to use webHttpBinding
unless you tell him.
<services>
<service name="Service1">
<endpoint address=""
binding="webHttpBinding"
contract="IService1" />
</service>
</services>
Link below provides detailed instructions for hosting service in IIS (with wsHttpBinding
). You just need to use webHttpBinding
instead of wsHttpBinding
-
http://msdn.microsoft.com/en-us/library/ms733766.aspx
I hope your service is running in another domain from where you are consuming it. You have to use JSONP calls in those cases.
Modify the dataType
to jsonp
.
$.ajax({
//..
dataType: "jsonp",
//..
});
Thanks for all the responses. Surprisingly enough, I managed to fix the error, but the solution was totally not what I was expecting. I had to add an additional attribute to the markup of the Service1.svc file:
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory
I am not sure why this wasn't automatically added to the file when the project was built, but thats what did it. I am now able to invoke the Test method through the browser as well as through my AJAX request with no problem.
Thanks again for everybody's help.