【问题标题】:Passing JSON to WCF via Ajax Call通过 Ajax 调用将 JSON 传递给 WCF
【发布时间】:2018-06-24 16:27:26
【问题描述】:

我在网上搜索了有关如何正确地将 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>

帮助!! (或者我必须使用节点!:))

【问题讨论】:

  • 如果要POST,不要把post数据放在URL里,放在data:

标签: javascript json ajax wcf restful-authentication


【解决方案1】:

问题是您正在尝试对已经是字符串格式的数据进行字符串化。删除 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);

【讨论】:

  • 感谢您的建议。我已经尝试了上述方法,但仍然是 400。请记住,我从创建对象开始并使用 JSON.stringify 对其进行转换。它完美地转换,但在 POST 上仍然失败。错误
  • 保持原样并在答案中检查更新的 uri 路径
  • 还是不行!这是 Chrome Debug 中的错误,...index.html#:1 Failed to load localhost:12109/WorkDataService.svc/UpsertWorkData/…: Response for preflight has invalid HTTP status code 400
  • 我在下一行对 workDataAsJson 变量进行了如下编码:\n\n workDataAsJson = JSON.stringify({"TestData":"121"}); workDataAsJson = encodeURIComponent(workDataAsJson); \n\n 还是不行!
  • preflight - CORS 问题 - CORS 预检是 OPTIONS 请求,您的服务器不处理 OPTIONS 请求 - 您需要处理 OPTIONS 跨源请求请求
猜你喜欢
  • 2011-01-23
  • 1970-01-01
  • 2021-08-06
  • 2020-01-27
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多