为什么我的WCF调用不返回JSON?

时间:2011-10-11 17:54:05

标签: c# wcf json

我从这里跟踪了在线示例,Google没有成功:意味着我已经尝试了各种配置但无济于事。

真心感谢任何帮助。

谢谢!

更新
我真的只想从Web服务中捕获JSON。因此,如果我没有将WCF服务配置为REST-ful服务,那么对我来说没关系。

HTML侧视图:

<script type="text/javascript">
    <!--
        var pageController =
        (function ($) {
            var publicInstances = {};

            publicInstances.controller = controller;
            function controller() {

                var self = this;

                self.form = null;
                self.wcfService = 'http://localhost:2798/Service.svc';

                self.Type = null;           // GET or POST or PUT or DELETE verb
                self.Url = null;            // Location of the service
                self.Data = null;           // Data sent to server
                self.ContentType = null;    // Content type sent to server
                self.DataType = null;       // Expected data format from server
                self.ProcessData = null;    // True or False

                this.initialize = function () {
                    self.form = new form(self);
                };

                this.invoke = function (onSuccess) {
                    $.ajax({
                        type: self.Type,
                        url: self.Url,
                        data: self.Data,
                        contentType: self.ContentType,
                        dataType: self.DataType,
                        processData: self.ProcessData,
                        complete: self.onComplete,
                        error: self.onError,
                        success: onSuccess
                    });
                };
                this.onComplete = function (xmlHttpRequest, status) {
                    alert("onComplete");
                };
                this.onError = function (xmlHttpRequest, status, error) {
                    alert("onError");
                };

                this.listPeople = function () {
                    self.Type = 'POST';
                    self.Url = self.wcfService + '/ListPeople';
                    self.Data = null;
                    self.ContentType = 'application/json; charset=utf-8';
                    self.DataType = 'json';
                    self.ProcessData = true;

                    self.invoke(self.dataBindListPeople);
                };
                this.dataBindListPeople = function (data, status, xmlHttpRequest) {
                    // This runs but no repsonse exists???
                    alert("dataBindListPeople");
                };

                self.initialize();
            };

            publicInstances.form = form;
            function form(controller) {

                var self = this;

                self.controller = controller;

                self.btnListPeople = $('#btnListPeople');

                this.initialize = function () {
                    self.btnListPeople.click(self.listPeople);
                };

                this.validate = function () { return true; };
                this.disable = function () { };
                this.enable = function () { };

                this.listPeople = function () {
                    if (self.validate());
                    self.controller.listPeople();
                };

                this.populateListPeople = function (json) {
                    alert("populateListPeople");
                };

                self.initialize();
            };

            return publicInstances;
        })(jQuery);

        var defaultPage = null;

        $j(document).ready(function () {
            defaultPage = new pageController.controller();
            var stop = "";
        });
    -->
    </script>

<input type="button" id="btnListPeople" value="List People" />

web.config看起来像:
当我将SERVICE REFERENCE添加到项目中时,这是自动创建的。

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService" 
                 closeTimeout="00:01:00"
                 openTimeout="00:01:00" 
                 receiveTimeout="00:10:00" 
                 sendTimeout="00:01:00"
                 allowCookies="false" 
                 bypassProxyOnLocal="false" 
                 hostNameComparisonMode="StrongWildcard"
                 maxBufferSize="65536" 
                 maxBufferPoolSize="524288" 
                 maxReceivedMessageSize="65536"
                 messageEncoding="Text" 
                 textEncoding="utf-8" 
                 transferMode="Buffered"
                 useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" 
                        maxStringContentLength="8192" 
                        maxArrayLength="16384"
                        maxBytesPerRead="4096" 
                        maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:2798/Service.svc" 
                binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IService" 
                contract="ServiceReference1.IService"
                name="BasicHttpBinding_IService" />
    </client>
  </system.serviceModel>

WCF服务方面看起来像:

namespace WcfService
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
        List<Person> ListPeople();
    }
}

namespace WcfService
{
    [DataContract]
    public class Person
    {
        public Person(string firstName, string lastName, int age)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
        }

        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public int Age { get; set; }
    }
}

namespace WcfService
{
    [ServiceBehavior]
    public class Service : IService
    {
        public List<Person> ListPeople()
        {
            List<Person> people = new List<Person>();
            people.Add(new Person("Peyton", "Manning", 35));
            people.Add(new Person ("Drew", "Brees", 31));
            people.Add(new Person("Brett", "Favre", 58));

            return people;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

你在这里混合了两个不相容的世界......

1)在您的配置中定义basicHttpBinding - 这是 SOAP 绑定,而SOAP不适合从jQuery或Javascript调用。它通常还会返回 XML (而不是JSON)

2)但是,在您的服务合同中,您似乎指的是基于REST的WCF:

 [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, 
            ResponseFormat = WebMessageFormat.Json)]

但为了使其正常工作,您需要使用基于REST的绑定 - webHttpBinding(可能还有合适的WebServiceHostFactory和/或可能的<webHttp />端点行为。< / p>

您应该转到WCF REST Developer Center on MSDN以了解如何正确设置将WSON返回给您的来电者的REST WCF服务!