代码改变世界

WCF 4.0 REST Service JSON跨域调用

2011-05-18 13:26  我来看看  阅读(1296)  评论(2编辑  收藏  举报

 最近在项目中用到了 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格式。