您的位置:首页 > Web前端 > JavaScript

WCF 4.0 REST Service JSON跨域调用

2012-08-21 09:17 363 查看
[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>


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

类文件中添加[JavascriptCallbackBehavior(UrlParameterName="callback")]

配置文件的 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”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: