熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> ASP編程 >> 正文

ExtJs與WCF之間的跨域訪問

2013-11-15 12:49:21  來源: ASP編程 

  在前面文章ExtJs與WCF之間的跨域訪問已經通過服務端代理的方式解決了ExtJs與WCF跨域訪問的問題那個方案看起來並不怎麼優雅而當我在寫過用Restful方式調用WCF進行上傳下載後愕然發現原來WCF支持原生數據(Raw)的返回這就解決了ExtJs與Wcf之間進行跨域調用中的難題返回數據必須滿足<script>格式下面根據ExtJs與WCF之間的跨域訪問中實現的項目通過Stream和ContentType的聯合使用返回原生數據給Extjs從而實現跨域調用

  第一步在PageGridServicesvc後台代碼中添加操作契約GetProductsByPageCorssDomain代碼為                  [OperationContract]
                [WebInvoke(Method = * ResponseFormat = WebMessageFormatJson
               UriTemplate = GetProductsByPageCorssDomain?start={start}&limit={limit}&callback={callback})]
                public Stream GetProductsByPageCorssDomain(int start int limitstring callback)
                {
                    ProductsDataContext productDbContext = new ProductsDataContext();
                    IQueryable<Product> res = productDbContextProductSelect(product => product);
                    PageData<Product[]> returnData = new PageData<Product[]>();
                    returnDataTotolRecord = resToArray<Product>()Length;
                    res = resSkip<Product>(start);
                    res = resTake<Product>(limit);
                    returnDataData = resToArray<Product>();
                    SystemRuntimeSerializationJsonDataContractJsonSerializer formater = new SystemRuntimeSerializationJsonDataContractJsonSerializer(typeof(PageData<Product[]>));
                    MemoryStream ms = new MemoryStream();
                    formaterWriteObject(ms returnData);
                    msPosition = ;
                    StreamReader sr = new StreamReader(ms);
                    string objContent = srReadToEnd();
                    string returnStr = callback+(+objContent+);
                    srClose();
                    ms = new MemoryStream();
                    StreamWriter sw = new StreamWriter(ms);
                    swAutoFlush = true;
                    swWrite(returnStr);
                    msPosition = ;
                    WebOperationContextCurrentOutgoingResponseContentType = text/plain;
                    return ms;
                }

  第二步在項目中創建一個新的htm頁面PageGridCo代碼為          <!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN transitionaldtd>
        <html xmlns= >
        <head>
            <title>ExtJs+WCF+LINQ打造分頁Grid</title>
            <link rel=stylesheet type=text/css />
            <script type=text/javascript src=adapter/ext/extbasejs charset=gb></script>
            <script type=text/javascript src=extalldebugjs charset=gb></script>
            <link rel=stylesheet type=text/css />
            <script type=text/javascript src=shared/examplesjs charset=gb></script>
            <script type=text/javascript src=PageGridCrossDomainWithRowjs charset=gb></script>
        </head>
        <body>
            <h>
                ExtJs+WCF+LINQ打造分頁跨域Grid</h>
            <div id=pagegrid>
            </div>
        </body>
        </html>

  第三步在項目中創建一個新的js腳本文件PageGridCrossDomainWithRowjs

            /*
         * Ext JS Library
         * Copyright(c) Ext JS LLC
         *
         *
         *
         */
         ExtonReady(function(){
           var proxy = new ExtdataScriptTagProxy({
             url:
           });
           var reader = new ExtdataJsonReader(
             {root:DatatotalProperty :TotolRecord}
             [
               {name: ProductID}
               {name: Name}
               {name: ProductNumber}
               {name: MakeFlag}
               {name: FinishedGoodsFlag}
               {name: Color}
               {name: SafetyStockLevel}
               {name: ReorderPoint}
               {name: StandardCost}
               {name: ListPrice}
               {name: Size}
               {name: SizeUnitMeasureCode}
               {name: Weight}
               {name: DaysToManufacture}
               {name: ProductLine}
               {name: Class}
               {name: Style}
               {name: Weight}
               {name: ProductSubcategoryID}
               {name: ProductModelID}
               {name: SellStartDate}
               {name: SellEndDate}
               {name: DiscontinuedDate}
               {name: rowguid}
               {name: ModifiedDate}
             ]
           );
           var store = new ExtdataStore(
             {proxy:proxyreader:reader}
           );
           // create the Grid
            var grid = new ExtgridGridPanel({
                store: store
                columns: [
                    {id:ProductIDheader: 編號width: sortable: true dataIndex: ProductID}
                    {header: 名稱 width: sortable: true dataIndex: Name}
                    {header: 產品編碼 width: sortable: true dataIndex: ProductNumber}
                    {header: 是否標記 width: sortable: true dataIndex: MakeFlag}
                    {header: 顏色 width: sortable: truedataIndex:Color}
                    {header: 數量 width: sortable: truedataIndex:ReorderPoint}
                    {header: 單價 width: sortable: truerenderer:userMoneydataIndex: StandardCost}
                ]
                stripeRows: true
                autoExpandColumn: ProductID
                height:
                width:
                title:產品信息
                viewConfig:
                {
                  columnsText:
                  sortAscText:升序
                  sortDescText:降序
                }
                bbar: new ExtPagingToolbar({
                    pageSize:
                    store: store
                    displayInfo: true
                    displayMsg: 總記錄數 {} {} of {}
                    emptyMsg: 沒有記錄
                })
            });
            gridrender(pagegrid);
            //載入
            storeload({params:{start:limit:}});
            gridgetSelectionModel()selectFirstRow();
         });

  接下來浏覽PageGridCo便可以得到如下運行結果

  兩種方案對比

  第一種方案要通過服務端WebClient訪問WCF服務然後由ExtJs訪問本地代理頁面這樣勢必造成一些性能損失而本文的方式無須架設服務端代理由ExtJs直接請求WCF從操作復雜度上要低一下理論上也能因此提高一些性能從實現原理上第一種方式有些背離ExtJs的設計初衷ExtJS強調用ScriptTagProxy跨域訪問數據但這樣對數據格式有一定要求第一種方案采用繞過攔路虎的方式通過一個中轉將跨域問題化解掉了雖然效果達到但畢竟沒有充分利用到ExtJs的ScriptTagProxy而且違背了WCF中的Restful訪問方式
 
  上面兩點都是說明第一種方案的缺點本文方案的優點但在現實中考慮到可用性還是建議用第一種方式的本文這種方式雖然有一定優點卻大大破壞了WCF程序結構使得WCF服務程序開發難度加大且以後難於維護因為一個服務他的使命不光光針對ExtJs一方的調用他的消費者可能很多消費方式也不僅僅局限在Restful上更多需求可能體現在SOAP方式上他消費者所在平台也可能是linux這樣事情就變的復雜起來一個返回stream的操作具有普遍性麼?對於其他消費者stream友好麼?而且設置了ContentType是不是對其他消費者有致命影響呢?這些問題都是要考慮的如果是一個面向大眾的服務考慮到上面的問題縱是有千萬種理由這種方案還是不可取的相比較一點點的性能更有些得不償失!當然具體情況要具體分析如果是專門為ExtJs或者其他Ajax設計的那本文方案就比較合理了


From:http://tw.wingwit.com/Article/program/ASP/201311/21689.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.