javascript - 通过 Ajax 调用将 JSON 传递给 WCF

标签 javascript json ajax wcf restful-authentication

我在网上搜索了有关如何正确将 JSON 字符串发送到 WCF 服务的说明。我的应用程序有十几个 GET,它们都工作得很好,但我无法让 POST 到达调试器。我已经归结为最简单的 JSON 字符串,但在 chrome 浏览器中仍然收到 400 错误。

请看下面,...

JS:

 workDataAsJson = JSON.stringify('{"TestData":"121"}');
    $.ajax({      
      type: "POST",
      async: true,
      cache: false,
      timeout: webCallDefaultTimeout,
      contentType: "application/json; charset=utf-8",
      url: baseUrl.concat('UpsertWorkData/' + workDataAsJson),                      
      dataType: "json",
      success: function (response, status, jqXHR) {     
        if (status == 'success') {
            var workplanData = $.parseJSON(response);                 
            // notify user of success,...

        } else {
          displayGenericModal('Web Service Error', 'Uh Oh! Unable to Connect to the Database to Obtain Work Data');
        }
      },
      error: function (response, status, jqXHR) {
          displayGenericModal('Web Service Error', 'Uh Oh! Unable to Connect to the Database to Obtain Work Data');          
      }        
  });    
  } catch(ex) {
    alert(ex);
  }

现在对于 WCF 操作合约,...

    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", UriTemplate = "UpsertWorkData/{WorkData}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string UpsertWorkData(string WorkData);

好的,现在介绍 web.config 文件。别笑,我基本上把我读过的所有东西都扔了!

<?xml version="1.0"?>
<configuration>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483644"/>
      </webServices>
    </scripting>
  </system.web.extensions>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.5" />
      </system.Web>
  -->
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5" maxRequestLength ="798778" maxUrlLength="779779" enable="true"/>
  </system.web>
  <system.serviceModel>
      <services>
        <service name="WorkDataService.Service1">
        <endpoint address="" binding="webHttpBinding"  bindingConfiguration="" behaviorConfiguration="restfulBehaviour" name="ServicesEndpoint" contract="WorkDataService.IWorkDataService" />          
      </service>
    </services>
    <behaviors>        
        <endpointBehaviors>
          <behavior name="restfulBehaviour">            
          <webHttp />

          </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
    <bindings>
      <webHttpBinding>
        <binding maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="200" maxStringContentLength="83886089" maxArrayLength="163841" maxBytesPerRead="2147483647" maxNameTableCharCount="16384"/>
        </binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
       <httpProtocol>
       <customHeaders>
         <add name="Access-Control-Allow-Origin" value="*" />
       </customHeaders>
   </httpProtocol>
  </system.webServer>
</configuration>

救命!! (或者我必须使用节点!:))

最佳答案

问题是您正在尝试对已经是字符串格式的数据进行字符串化。删除 JSON.stringify

workDataAsJson =  '{"TestData":"121"}';

workDataAsJson = JSON.stringify({"TestData":"121"});

此外,uri 应更改为

  [OperationContract]    
  [WebInvoke(Method = "POST",
  UriTemplate = "/UpsertWorkData",
  RequestFormat = WebMessageFormat.Json,
  ResponseFormat = WebMessageFormat.Json,
  BodyStyle = WebMessageBodyStyle.Bare)]     
  string UpsertWorkData(string WorkData);

关于javascript - 通过 Ajax 调用将 JSON 传递给 WCF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48273184/

相关文章:

javascript - 在 Node.js 中发送带有请求的 JSON

javascript - jQuery - AJAX POST 请求给出 500 内部服务器错误

javascript - Visual Studio 2013 中的 Angular Material 图标注册

javascript - 用 Javascript 计算假期

javascript - 我可以使用哪些 highstock 选项来删除 xAxis 之间的内容

javascript - 在react.js中将no-cors包含到 header 中以获取json内容时出现奇怪的错误

javascript - 为什么我的 javascript Promise 卡在 "pending"上?

jquery - 如何从 jQuery 中的 Web 服务返回的 JSON 中提取值?

php - 根据所做的选择选择框加载

javascript - 在 jQuery 中将数组从一个函数传递到另一个函数