WCF 4.0 REST Service JSON跨域调用

本文介绍如何通过简单配置使WCF 4.0 REST服务支持跨域请求。只需在服务类添加特定特性,并在配置文件中启用跨域脚本访问即可实现跨域调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值