将asmx Web服务转换为WCF Web服务 - 为什么JSON参数需要额外的引号?

时间:2011-05-30 00:54:19

标签: wcf web-services json asmx

我有一个asmx网络服务,它返回一个非洲大陆的国家/地区列表。使用JQuery调用我使用的Web服务时:

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "InternationalLookup.asmx/LoadCountries",
            data: '{ continentName: "' + $(this).val() + '" }',
            dataType: "json",
            success: function (response) {
                //..code
            },
            error: function (response) {
                //..code
            }
        });

这适用于asmx代码,但在使用WCF服务时,我必须将其更改为:

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "InternationalLookup.svc/LoadCountries",
            **data: '{ \"continentName\": "' + $(this).val() + '" }',**
            dataType: "json",
            success: function (response) {
                //..code
            },
            error: function (response) {
                //..code
            }
        });

请注意我必须传入的数据的差异,现在需要在大陆名称周围添加额外的引号。我的WCF服务及其配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="InternationalLookupBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="InternationalLookup">
      <enableWebScript />
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="InternationalLookupBehavior"
      name="USQ.Websites.RefreshLayout.Webservices.UsqInternationalLookup">
    <endpoint address="" binding="wsHttpBinding" contract="IInternationalLookup">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>

[ServiceContract]
public interface IInternationalLookup
{
    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string LoadCountries(string continentName);
}

尽管有一些麻烦使它工作,我想知道为什么WCF Web服务的参数必须用其他引号括起来。

1 个答案:

答案 0 :(得分:0)

JSON规范规定对象成员名称必须用双引号括起来 - 请参阅www.json.org - 这就是WCF强制执行的内容。我不知道为什么ASMX服务使用的JSON解析器在执行语法时选择更加宽松。

相关问题