вызов службы WCF из JQuery возвращает 400 неверных запросов - PullRequest
0 голосов
/ 16 июня 2020

Я пытаюсь позвонить из веб-службы WCF, используя jquery, но это всегда терпит неудачу с неверным запросом 400.

Как служба WCF, так и веб-сайт развернуты на одном сервере с использованием IIS.

ошибка, которую я получаю в консоли при вызове веб-метода WCF:

Не удалось загрузить ресурс: сервер ответил статусом 400 (неверный запрос)

мой файл конфигурации службы WCF:

 <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>

контракт операции внутри IService1.cs

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

my javascript код:

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 Ответ

0 голосов
/ 17 июня 2020

Есть два решения, Первое решение:

Вы можете удалить "BodyStyle". Если вы используете "BodyStyle", вам необходимо изменить JSON.

Второе решение:

Если вы не хотите удалять "bodystyle", вам необходимо изменить переданный формат JSON следующим образом:

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