【问题标题】:How to natively enable JSONP for existing WCF service?如何为现有的 WCF 服务原生启用 JSONP?
【发布时间】:2012-01-03 09:51:01
【问题描述】:

我有一个类似以下方法的现有服务:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class SomeService : ISomething
{
    public SomeListResults SomeList(SomeParams someParams)
    {
          ....
    }
}

是否有一种简单的方法可以同时允许 JSONP 调用和 JSON(检测它)。这是本地人吗?

【问题讨论】:

    标签: c# asp.net wcf json jsonp


    【解决方案1】:

    新的 JSONP 功能通过 WebHttpBinding 公开。 CustomersService 的配置如下所示:

     <bindings>
        <webHttpBinding>
          <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
        </webHttpBinding>
      </bindings>
      <services>
        <service name="ServiceSite.CustomersService">
          <endpoint address="" binding="webHttpBinding"
                    bindingConfiguration="webHttpBindingWithJsonP" contract="ServiceSite.CustomersService"
                    behaviorConfiguration="webHttpBehavior"/>
        </service>
      </services>
    

    通过 jQuery 使用 JSONP

     // Get the JsonP data
     $.getJSON('http://localhost:65025/CustomersService.svc/GetCustomers?callback=?', null, function (customers) {
          alert('Received ' + customers.length + ' Customers');
     });
    

    【讨论】:

      【解决方案2】:

      将您的配置更新为如下所示:

      <configuration>
        <system.web>
          <compilation debug="true" targetframework="4.0">
          <authentication mode="None">
        </authentication></compilation></system.web>
        <system.webserver>
          <modules runallmanagedmodulesforallrequests="true">
        </modules></system.webserver>
        <system.servicemodel>
          <servicehostingenvironment **aspnetcompatibilityenabled**="true">
          <standardendpoints>
            <webscriptendpoint>
              <standardendpoint **crossdomainscriptaccessenabled**="true" name="">
            </standardendpoint></webscriptendpoint>
          </standardendpoints>
        </servicehostingenvironment></system.servicemodel>
      </configuration>
      

      See here for a blog post 提供了创建可跨域访问的 wcf 服务的演练。

      这将使您的服务能够接受来自跨域来源的请求。

      在确定是否填充您的响应(jsonp中的p)方面,

      感谢@carlosfigueira:

      如果使用原生支持的 .Net 4 JSONP。只要请求有一个名为“callback”的查询字符串参数(这个名字可以配置),响应就会用函数名填充 .

      否则,您需要编写一个自定义消息检查器来适当地填充响应。

      【讨论】:

      • 您不需要编写自定义检查器 - 在 .NET 4.0 中原生支持 JSONP。只要请求有一个名为“callback”的查询字符串参数(这个名称可以配置),响应就会用函数名称填充(假设你提到的crossDomainScriptAccessEnabled设置为true)
      • @carlosfigueira 非常感谢您提供这些信息,我最后一次涉足 jsonp 和 WCF 世界是在 .Net 3.5 中。答案现已更新。顺便说一句,很棒的博客!
      猜你喜欢
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 2010-12-16
      • 2012-09-26
      • 1970-01-01
      • 2011-09-24
      • 2011-06-02
      相关资源
      最近更新 更多