大家可能对理论的知识都很熟,但是往往实践起来就很困难,我们平时就要把实践和理论相结合,在前面文章WCF与ExtJs之间的跨域访问已经通过服务端代理的方式解决了WCF与ExtJs跨域访问的问题。
#T#那个方案看起来并不怎么优雅,而当我在写过用Restful方式调用WCF进行上传下载后,愕然发现原来WCF支持原生数据(Raw)的返回,这就解决了ExtJs与Wcf之间进行跨域调用中的难题:返回数据必须满足<script>格式。下面根据WCF与ExtJs之间的跨域访问中实现的项目,通过Stream和ContentType的联合使用,返回原生数据给Extjs,从而实现跨域调用。
***步:在PageGridService.svc后台代码中,添加操作契约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;
- resres = res.Skip<Product>(start);
- resres = 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,代码为:
- <!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>