WCF 4.0 REST Service JSON跨域调用

 最近在项目中用到了 WCF4.0 REST。在跨域调用时走了不少弯路,查了不少技术强人的文章,其实它真的就这么容易。好了不废话了直接贴代码。

 调用的服务类:

 1      [ServiceContract]
 2      [AspNetCompatibilityRequirements(RequirementsMode  =  AspNetCompatibilityRequirementsMode.Allowed)]
 3      [ServiceBehavior(InstanceContextMode  =  InstanceContextMode.PerCall)]
 4      [JavascriptCallbackBehavior(UrlParameterName = " callback " )]
 5       public   class  Writing
 6      {
 7 
 8          [WebGet(UriTemplate = "" , ResponseFormat = WebMessageFormat.Json)]
 9           public  List < Top >  GetCollection()
10          {
11              WritingContext _context  =   new  WritingContext();
12 
13               return  _context.Database
14                  .SqlQuery < Top > ( " SELECT TOP 15 WRITINGID Id, WRITING Title FROM YC_WRITING ORDER BY WRITINGID DESC " )
15                  .ToList();
16          }
17      }

 

  配置文件:
 1     < system.serviceModel >
 2       < serviceHostingEnvironment  aspNetCompatibilityEnabled ="true" />
 3       < standardEndpoints >
 4         < webHttpEndpoint >
 5           <!--  
 6              Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
 7              via the attributes on the <standardEndpoint> element below
 8           -->
 9           < standardEndpoint  name =""  helpEnabled ="true"  automaticFormatSelectionEnabled ="false"  
10                            crossDomainScriptAccessEnabled ="true" />
11         </ webHttpEndpoint >
12       </ standardEndpoints >
13     </ system.serviceModel >

 

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

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

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

转载于:https://www.cnblogs.com/mickeyooo/archive/2011/05/18/wcf_4_rest_services_jsonp.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值