WCF與ExtJs實現(xiàn)項目分析
大家可能對理論的知識都很熟,但是往往實踐起來就很困難,我們平時就要把實踐和理論相結合,在前面文章WCF與ExtJs之間的跨域訪問已經通過服務端代理的方式解決了WCF與ExtJs跨域訪問的問題。
#T#那個方案看起來并不怎么優(yōu)雅,而當我在寫過用Restful方式調用WCF進行上傳下載后,愕然發(fā)現(xiàn)原來WCF支持原生數(shù)據(jù)(Raw)的返回,這就解決了ExtJs與Wcf之間進行跨域調用中的難題:返回數(shù)據(jù)必須滿足<script>格式。下面根據(jù)WCF與ExtJs之間的跨域訪問中實現(xiàn)的項目,通過Stream和ContentType的聯(lián)合使用,返回原生數(shù)據(jù)給Extjs,從而實現(xiàn)跨域調用。
***步:在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;
- }
第二步:在項目中創(chuàng)建一個新的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>