简体   繁体   English

从 JQuery 调用 WCF 服务返回 400 错误请求

[英]calling WCF service from JQuery returns 400 bad request

I'm trying to make a call from WCF web service using jquery but it always fails with 400 bad request.我正在尝试使用 jquery 服务从 WCF web 服务拨打电话,但它总是因 400 错误请求而失败。

Both the WCF Service and the website is deployed on the same server using IIS. WCF 服务和网站都使用 IIS 部署在同一台服务器上。

the error I'm getting in the console when calling the WCF web method:调用 WCF web 方法时我在控制台中遇到的错误:

Failed to load resource: the server responded with a status of 400 (Bad Request)加载资源失败:服务器响应状态为 400(错误请求)

my WCF service config file:我的 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>

the operation contract inside IService1.cs IService1.cs里面的操作契约

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

my javascript code:我的 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);
    }

}

There are two Solution, First Solution:有两个解决方案,第一个解决方案:

You can remove "BodyStyle",If you use "BodyStyle",you need modify your JSON.您可以删除“BodyStyle”,如果您使用“BodyStyle”,您需要修改您的 JSON。

Second Solution:第二种解决方案:

If you do not want to remove "bodystyle", you need to modify the JSON format passed in as follows:如果不想去掉“bodystyle”,需要修改传入的JSON格式如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM