Ответ WCF в формате JSON вместо JSONP

Хорошо, я использую службу WCF для обработки запросов от своего веб-приложения и отвечаю в формате JSONP. Я перепробовал все решения, которые смог найти, изучил документацию (http://msdn.microsoft.com/en-us/library/ee834511.aspx#Y200) и пример проекта.

Проблема заключается в том, что объект ответа (json) не упаковывается с обратным вызовом, указанным в URL-адресе.

Запрос такой:

http://localhost/socialApi/socialApi.svc/api/login?callback=callback&username=AAAAA&password=BBBB

Web.config выглядит следующим образом:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <trace enabled="true"/>
    <compilation debug="true" targetFramework="4.0"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*************" /></assemblies></compilation>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service name="RestService.socialApi">
        <endpoint address="" binding="webHttpBinding" contract="RestService.IsocialApi" bindingConfiguration="webHttpBindingJsonP" behaviorConfiguration="webHttpBehavior">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="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="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior" >
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>        
        <binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true"/>
      </webHttpBinding>
    </bindings>
    <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
  </system.serviceModel>
  <system.webServer>
   <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <connectionStrings>
    <add name="AsrAppEntities" connectionString="myconstring**********" />
  </connectionStrings>
</configuration>

И мой операционный контракт:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;

namespace socialApi
{
    [ServiceContract]
    public interface IsocialApi
    {
        [OperationContract]
        [WebGet(
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/api/login?username={username}&password={password}")]
        JsonpAuthenticationResponse Login(string username, string password);

    }
}

Ответ — обычный json:

{"Message":"unauthorized","Status":400,"Token":null}

И я хочу:

callbackfunction({"Message":"unauthorized","Status":400,"Token":null})

Я думаю, что это как-то связано с Web.config, потому что, когда я изменяю пример и настраиваю Web.config так, чтобы он выглядел как мой, пример больше не работает. Вы бы сказали, что я точно определил проблему... но нет.

Чтобы предоставить как можно больше информации, вот рабочее решение из примера:

Web.config:

<?xml version="1.0"?>
<!-- Copyright (c) Microsoft Corporation.  All rights reserved. -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="None" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
      </webScriptEndpoint>
    </standardEndpoints>
  </system.serviceModel>
</configuration>

И класс:

//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace Microsoft.Samples.Jsonp
{
    [DataContract]
    public class Customer
    {      
        [DataMember]
        public string Name;

        [DataMember]
        public string Address;
    }


    [ServiceContract(Namespace="JsonpAjaxService")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CustomerService
    {
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public Customer GetCustomer()
        {
           return new Customer() { Name="Bob", Address="1 Example Way"};
        }
    }
}

Приведенный выше пример возвращает объект jsonp. Это вызов из примера:

function makeCall() {
            var proxy = new JsonpAjaxService.CustomerService();
            proxy.set_enableJsonp(true);
            proxy.GetCustomer(onSuccess, onFail, null);
        }

proxy.set_enableJsonp (истина); может быть, я что-то упускаю в своем звонке? Но я не могу добавить это в свой вызов, потому что я не вызываю службу из того же решения.

Итак, есть идеи о том, что вызывает нормальный ответ JSON вместо запроса JSONP?


person Gerard    schedule 14.04.2011    source источник


Ответы (1)


Проблема была в заводских настройках. В разметке файла svc мне пришлось изменить фабрику на System.ServiceModel.Activation.WebScriptServiceHostFactory.

person Gerard    schedule 26.04.2011