2011-10-11 4 views
1

Я следил за онлайн-примерами здесь и Google без успеха: это означает, что я экспериментировал с различными конфигурациями безрезультатно.Почему мой вызов WCF не возвращает JSON?

Любую помощь можно получить по-настоящему.

СПАСИБО!

UPDATE:
Я просто хочу, чтобы захватить JSON из веб-службы. Поэтому, если мне не нужно настраивать службу WCF как услугу REST-ful, то это нормально со мной.

HTML-SIDE выглядит следующим образом:

<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, выглядит следующим образом:
Это был создан автоматически, когда я добавил ссылку на службу в проект.

<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> 

ФОС SERVICE SIDE выглядит следующим образом:

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; 
     } 
    } 
} 

ответ

3

Вы смешиваете две несовместимые миры здесь ...

1) в вашей конфигурации вы определяете basicHttpBinding - это a SOAP привязка, а SOAP не подходит для вызова из jQuery или Javascript. Она, как правило, также возвращает XML (не JSON)

2) в контракте услуг однако, как представляется вам иметь в виду REST на основе WCF:

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

, но для того, чтобы это работало, необходимо использовать REST на основе связывания. - webHttpBinding (и, возможно, подходящий WebServiceHostFactory и/или, возможно, поведение <webHttp /> конечной

Вы должны пойти к WCF REST Developer Center on MSDN, чтобы узнать, как правильно настроить REST службы WCF, которая возвращает JSON вашим абонентам!

+0

Я просто хочу, чтобы он вернулся JSON. Должен ли я по-прежнему настраиваться как RESTFUL? –

+0

@ PrisonerZERO: Да, я бы хотел - JSON лучше всего подходит для службы WCF ** REST **. –

+1

Я ценю помощь. Благодаря! –

Смежные вопросы