0
votes

I'm trying to make a call from WCF web service using jquery but it always fails with 400 bad request.

Both the WCF Service and the website is deployed on the same server using IIS.

the error I'm getting in the console when calling the WCF web method :

Failed to load resource: the server responded with a status of 400 (Bad Request)

my WCF service config file:

 <configuration>

  <connectionStrings>

    <add name="ConnectionString"... />

  </connectionStrings>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
    <add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
  </appSettings>


  <system.web>
    <httpRuntime maxRequestLength="4000480" executionTimeout="600" />
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off" />
    <authentication mode="Windows" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
    <sessionState mode="Off" />
  </system.web>




  <system.webServer>



    <directoryBrowse enabled="true" />

   <rewrite>
      <rules>

        <rule name="Disable Service1.svc" stopProcessing="true">
          <match url="^Service1.svc(.*)$" />
          <action type="AbortRequest" />
        </rule>

        <rule name="Disable Service2.svc" stopProcessing="true">
          <match url="^Service2.svc(.*)$" />
          <action type="AbortRequest" />
        </rule>

        <rule name="Enable API2 Request">
          <match url="^API2/(.*)$" />
          <action type="Rewrite" url="Service2.svc/{R:1}" />
        </rule>
        <rule name="Enable API Request">
          <match url="^API/(.*)$" />
          <action type="Rewrite" url="Service1.svc/{R:1}" />
        </rule>

        <rule name="Enabldde API Request">
          <match url="^$" />
          <action type="Redirect" url="AccessDeniedPage.html" />
        </rule>

        <rule name="Enable Requesting Method Directly xml format2">
          <match url="^xml2/([a-zA-Z]*)$" />
          <action type="Rewrite" url="Service2.svc/xml2/{R:1}" />
        </rule>
        <rule name="Enable Requesting Method Directly xml format">
          <match url="^xml/([a-zA-Z]*)$" />
          <action type="Rewrite" url="Service1.svc/xml/{R:1}" />
        </rule>


        <rule name="Enable Requesting Method Directly through json2">
          <match url="^json/([a-zA-Z]*)$" />
          <action type="Rewrite" url="Service2.svc/json/{R:1}" />
        </rule>
        <rule name="Enable Requesting Method Directly through json">
          <match url="^([a-zA-Z]*)$" />
          <action type="Rewrite" url="Service1.svc/{R:1}" />
        </rule>


        <rule name="Remove trailing slash from main directory so that it doesnt open" stopProcessing="true">
          <match url="/$" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" redirectType="Permanent" url="{R:1}" />
        </rule>

        <rule name="Remove trailing slash from request" stopProcessing="true">
          <match url="(.*)/$" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" redirectType="Permanent" url="{R:1}" />
        </rule>

      </rules>

    </rewrite>


    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
      </customHeaders>
    </httpProtocol>

  </system.webServer>


  <system.serviceModel>
    <services>

     <service name="CLService.Service1" behaviorConfiguration="Service1Behavior">
        <endpoint address="unsecure/XML" binding="webHttpBinding" bindingConfiguration="webHttpBinding" contract="CLService.IService1" behaviorConfiguration="RestXMLEndpointBehavior"/>
        <endpoint address="unsecure" binding="webHttpBinding" bindingConfiguration="webHttpBinding" contract="CLService.IService1" behaviorConfiguration="RestJSONEndpointBehavior"/>

        <endpoint address="XML" binding="webHttpBinding" bindingConfiguration="webHttpsBinding" contract="CLService.IService1" behaviorConfiguration="RestXMLEndpointBehavior"/>
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpsBinding" contract="CLService.IService1" behaviorConfiguration="RestJSONEndpointBehavior"/>
       <endpoint address="json" binding="webHttpBinding" bindingConfiguration="webHttpsBinding" contract="CLService.IService1" behaviorConfiguration="RestJSONEndpointBehavior" />
      </service>


    </services>

    <behaviors>
      <endpointBehaviors>

        <behavior name="RestJSONEndpointBehavior">
          <webHttp helpEnabled="false" defaultOutgoingResponseFormat="Json" />

        </behavior>
        <behavior name="RestXMLEndpointBehavior">
          <webHttp helpEnabled="false" defaultOutgoingResponseFormat="Xml" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="Service1Behavior">
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug httpHelpPageEnabled="false" includeExceptionDetailInFaults="true" />
          <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="500" maxConcurrentInstances="600" />
        </behavior>
        <behavior name="">
          <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="500" maxConcurrentInstances="600" />
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <bindings>

      <webHttpBinding>

        <binding name="webHttpsBinding" crossDomainScriptAccessEnabled="true" maxBufferSize="2000000000" maxReceivedMessageSize="2000000000" transferMode="Buffered" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
          <readerQuotas maxDepth="250000000" maxStringContentLength="250000000" maxArrayLength="250000000" maxBytesPerRead="250000000" maxNameTableCharCount="250000000" />
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>

        <binding name="webHttpBinding" maxBufferPoolSize="9990000" maxBufferSize="2000000000" maxReceivedMessageSize="2000000000" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transferMode="Buffered">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />

          <security mode="None" />
        </binding>
      </webHttpBinding>

      <basicHttpBinding>
        <binding name="Service1Soap" />

        <binding name="secureHttpBinding">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </basicHttpBinding>

    </bindings>


    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="0" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

</configuration>

the operation contract inside IService1.cs

 [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "MyMethod", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        String MyMethod(String Query);

my javascript code:

function test(){
     try {

        code = getValuesWrittenInTheURLNew[0] + "";


        var QueryString = "Query=select value,Lat,Lng,elementID from myTable where code = '" + code + "'";

        $.ajax({
            type: "POST",
            async: true,
            url: IP + "/MyMethod",
            data: QueryString,
            dataType: "json",
            success: function (data) {

                console.log("d data: ",data);

            },
            failure: function (errMsg) {

                alert(errMsg);
                ResultCallBack();
            }

        });
    } catch (error) {
        console.log(error.message);
    }

}
1

1 Answers

0
votes

There are two Solution,First Solution:

You can remove "BodyStyle",If you use "BodyStyle",you need modify your JSON.

Second Solution:

If you do not want to remove "bodystyle", you need to modify the JSON format passed in as follows:

{
    "sitesMyMethod": [
        "Query=select value,Lat,Lng,elementID from myTable where code = '" + code + "'"
    ]
}