WCF與ExtJs實(shí)現(xiàn)項(xiàng)目分析
大家可能對(duì)理論的知識(shí)都很熟,但是往往實(shí)踐起來(lái)就很困難,我們平時(shí)就要把實(shí)踐和理論相結(jié)合,在前面文章WCF與ExtJs之間的跨域訪問已經(jīng)通過(guò)服務(wù)端代理的方式解決了WCF與ExtJs跨域訪問的問題。
#T#那個(gè)方案看起來(lái)并不怎么優(yōu)雅,而當(dāng)我在寫過(guò)用Restful方式調(diào)用WCF進(jìn)行上傳下載后,愕然發(fā)現(xiàn)原來(lái)WCF支持原生數(shù)據(jù)(Raw)的返回,這就解決了ExtJs與Wcf之間進(jìn)行跨域調(diào)用中的難題:返回?cái)?shù)據(jù)必須滿足<script>格式。下面根據(jù)WCF與ExtJs之間的跨域訪問中實(shí)現(xiàn)的項(xiàng)目,通過(guò)Stream和ContentType的聯(lián)合使用,返回原生數(shù)據(jù)給Extjs,從而實(shí)現(xiàn)跨域調(diào)用。
***步:在PageGridService.svc后臺(tái)代碼中,添加操作契約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;
- }
第二步:在項(xiàng)目中創(chuàng)建一個(gè)新的htm頁(yè)面: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打造分頁(yè)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打造分頁(yè)跨域Grid</h1>
- <div id="page-grid">
- </div>
- </body>
- </html>