在前面文章ExtJs与WCF之间的跨域访问已经通过服务端代理的方式解决了 ExtJs与WCF跨域访问的问题,那个方案看起来并不怎么优雅,而当我在写过用 Restful方式调用WCF进行上传下载后,愕然发现原来WCF支持原生数据(Raw)的返 回,这就解决了ExtJs与Wcf之间进行跨域调用中的难题:返回数据必须满足 <script>格式。下面根据ExtJs与WCF之间的跨域访问中实现的项目,通过 Stream和ContentType的联合使用,返回原生数据给Extjs,从而实现跨域调用。
第一步:在PageGridService.svc后台代码中,添加操作契约 GetProductsByPageCorssDomain,代码为:
GetProductsByPageCorssDomain方法
[OperationContract]
[WebInvoke(Method = "*", ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetProductsByPageCorssDomain?start={start}&limit={limit} &callback={callback}")]
public Stream GetProductsByPageCorssDomain(int start, int limit,string callback)
{
ProductsDataContext productDbContext = new ProductsDataContext();
IQueryable<Product> res = productDbContext.Product.Select(product => product);
PageData<Product[]> returnData = new PageData<Product[]>();
returnData.TotolRecord = res.ToArray<Product>().Length;
res = res.Skip<Product>(start);
res = res.Take<Product>(limit);
returnData.Data = res.ToArray<Product>();
System.Runtime.Serialization.Json.DataContractJsonSerializer formater = new System.Runtime.Serialization.Json.DataContractJsonSerializer (typeof(PageData<Product[]>));
MemoryStream ms = new MemoryStream();
formater.WriteObject(ms, returnData);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string objContent = sr.ReadToEnd();
string returnStr = callback+"("+objContent+")";
sr.Close();
ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.AutoFlush = true;
sw.Write(returnStr);
ms.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
return ms;
}
第二步:在项目中创建一个新的htm页面: PageGridCorssDomainWithRow.htm,代码为:
PageGridCorssDomainWithRow.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ExtJs+WCF+LINQ打造分页 Grid</title>
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css" />
<script type="text/javascript" src="adapter/ext/ext-base.js" charset="gb2312"></script>
<script type="text/javascript" src="ext-all-debug.js" charset="gb2312"></script>
<link rel="stylesheet" type="text/css" href="shared/examples.css" />
<script type="text/javascript" src="shared/examples.js" charset="gb2312"></script>
<script type="text/javascript" src="PageGridCrossDomainWithRow.js" charset="gb2312"></script>
</head>
<body>
<h1>
ExtJs+WCF+LINQ打造分页 跨域Grid</h1>
<div id="page-grid">
</div>
</body>
</html>