WCF 4.0 REST Service JSON跨域调用

[ServiceContract]
     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
     [JavascriptCallbackBehavior(UrlParameterName="callback")]
     public class Writing
     {
 
         [WebGet(UriTemplate="", ResponseFormat=WebMessageFormat.Json)]
         public List<Top> GetCollection()
         {
             WritingContext _context = new WritingContext();
 
             return _context.Database
                 .SqlQuery<Top>("SELECT TOP 15 WRITINGID Id, WRITING Title FROM YC_WRITING ORDER BY WRITINGID DESC")
                 .ToList();
         }
     }

<system.serviceModel>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
     <standardEndpoints>
       <webHttpEndpoint>
         <!-- 
             Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
             via the attributes on the <standardEndpoint> element below
         -->
         <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" 
                           crossDomainScriptAccessEnabled="true"/>
       </webHttpEndpoint>
     </standardEndpoints>
   </system.serviceModel>

真正实现夸域调用只需要两步:

  1. 类文件中添加[JavascriptCallbackBehavior(UrlParameterName="callback")]
  2. 配置文件的 standardEndpoint 添加 crossDomainScriptAccessEnabled="true"

最后需要注意的是WCF REST service 模板生成的配置文件automaticFormatSelectionEnabled属性默认是true,需要将其设置为false否则firefox里返回的将是xml格式。

     3.   如果你的防火墙是打开的 ,那么关闭防火墙 或者把此站点的端口加入例外哦

    4. Server Error in '/' Application.

Cross domain javascript callback is not supported in authenticated services.

  解决:

 

<system.web>
    <!--加上 mode ="None"-->
    <authentication mode="None"/>
  </system.web>

但是我测试的结果是: 

automaticFormatSelectionEnabled="true"  时

firefox            chrome            ie

             Json->json     Json->json          Xml->Xml

              Xml->Json      Xml->json           Json->页面错误

automaticFormatSelectionEnabled="false"  时

             Json->错误 Json->错误         Json->错误

             Xml->xml    Xml->xml               Xml->xml

在客户端,我们在一个Web页面中通过jQuery进行Ajax调用这个服务,并将得到的员工列表显示在一个表格中。出CSS之外的页面代码如下所示,需要注意的是在进行Ajax调用的使用将dataType选项设置成“jsonp”,而不是“json”。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值