WCF Web Service returns “Bad Request” error when invoked through Javascript

后端 未结 3 1742
悲哀的现实
悲哀的现实 2021-01-16 17:11

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

相关标签:
3条回答
  • 2021-01-16 17:51

    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.

    1. Add [WebGet] attribute got your operation
    2. Change binding in your endpoint - binding="webHttpBinding"
    3. Configure behavior for endpoint

    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

    0 讨论(0)
  • 2021-01-16 17:55

    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",
      //..
    });
    
    0 讨论(0)
  • 2021-01-16 17:57

    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.

    0 讨论(0)
提交回复
热议问题