啟用Ajax的wcf伺服器端與用戶端應用

來源:互聯網
上載者:User

一、先看一下程式結構圖與運行測試圖片如下:

1.程式結夠圖:

2.運行:

點擊Test按鈕調用wcf方法彈出調用返回結果

二、實現細節:我的開發環境(VS2010,.net4版本,其他版本沒有做過測試)

1.首先建立一個webapp應用程式,然後添加啟用ajax的wcf服務,

然後添加一個Test方法注意為該方法添加 [OperationContract] 與  [WebGet(RequestFormat=WebMessageFormat.Json)] 標籤關於WebGet標籤的詳細介紹參見:MSDN

其次要對該WCF類進列標籤修飾:[ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [JavascriptCallbackBehavior(UrlParameterName="JsonCallBack")] 尤其注意這兩個標籤,關於

AspNetCompatibilityRequirements說明:

在應用於服務實作類別時,此屬性可指示該服務是否需要 ASP.NET 相容模式,或是否支援為宿主應用程式定義域 (AppDomain) 啟用該相容模式。

AppDomains 宿主 服務可在兩種不同的宿主模式下運行:

  • 混合傳輸模式(預設):在這種模式下, 服務不參與 ASP.NET HTTP 管線。 這可保證 服務行為的一致性,使其不受宿主環境和傳輸的影響。

  • ASP.NET 相容模式:在這種模式下, 服務以與 ASMX 服務類似的方式參與 ASP.NET HTTP 管線。 ASP.NET 功能(例如,檔案授權、URL 授權和 HTTP 工作階段狀態)適用於在此模式下啟動並執行 服務。

宿主模式由應用程式級配置標誌 aspNetCompatibilityEnabled 控制。

<system.serviceModel>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

</system.serviceModel>

預設情況下,此標誌為 false,因此,除非明確選擇使用 相容模式,否則 ASP.NET 服務將在混合傳輸模式下運行。

有關以下內容的更多資訊ASP.NET 相容模式的更多資訊,請參見 serviceHostingEnvironment。

使用 RequirementsMode 屬性可以實現此目的。 運行時,應用程式可以通過檢查靜態屬性 AspNetCompatibilityEnabled 的值,來檢測是否啟用了 ASP.NET 相容模式。

JavascriptCallbackBehavior說明:

JSONP 是一種用於在 網頁瀏覽器中啟用跨網站指令碼支援的機制。 JSONP 涉及發送一個帶有作為 URL 查詢字串參數值提供的回呼函數名稱的請求。 相應的服務將返回一個響應,其中帶有封裝在對所提供的回呼函數的調用中的常規 JSON 負載(如同一行可執行代碼)。

以下是用於調用某個服務的 URL 的樣本:http://baseAddress/Service/RESTService?callback=functionName。 在調用該服務時,該服務將使用以下 JSON 進行響應:

functionName({ “root”:”Something});

JavascriptCallbackBehaviorAttribute 允許開發人員指定 URL 查詢字串參數的名稱來解釋為回調參數。 預設值是“callback”(不區分大小寫)。

到此為止wcf服務端代碼部分已經結束。

2.wcf服務端Webconfig配置,先把Demo的設定檔貼上來然後一點一點解釋:

<?xml version="1.0" encoding="utf-8"?><!--  有關如何配置 ASP.NET 應用程式的詳細訊息,請訪問http://go.microsoft.com/fwlink/?LinkId=169433  --><configuration>    <system.web>        <compilation debug="true" targetFramework="4.0" />      <!--添加:authentication,並設定為Forms-->          <authentication mode="Forms"/>    </system.web>    <system.serviceModel>        <behaviors>            <endpointBehaviors>                <behavior name="Wcf.demo.AjaxServiceAspNetAjaxBehavior">                    <enableWebScript />                </behavior>            </endpointBehaviors>          <!--添加serviceBehaviors-->          <serviceBehaviors>            <behavior name="EnableMetadataBehaviors">              <serviceMetadata httpGetEnabled="true"/>              <serviceDebug includeExceptionDetailInFaults="true"/>            </behavior>          </serviceBehaviors>          <!--添加serviceBehaviors:結束-->                  </behaviors>      <!--添加bindings-->      <bindings>        <webHttpBinding>          <binding name="test" crossDomainScriptAccessEnabled="true"></binding>        </webHttpBinding>      </bindings>      <!--添加bindings:結束-->              <serviceHostingEnvironment aspNetCompatibilityEnabled="true"            multipleSiteBindingsEnabled="true" />        <services>            <!--為service添加:behaviorConfiguration:中繼資料-->            <service name="Wcf.demo.AjaxService" behaviorConfiguration="EnableMetadataBehaviors">              <!--為endpoint添加:bindingConfiguration跨域-->                <endpoint address="" behaviorConfiguration="Wcf.demo.AjaxServiceAspNetAjaxBehavior"                  bindingConfiguration="test"   binding="webHttpBinding" contract="Wcf.demo.AjaxService" />            </service>        </services>        </services>    </system.serviceModel></configuration>

2.1添加 <authentication mode="Forms"/>身分識別驗證採用Forms驗證

2.2 添加服務端行為配置節

      <!--添加serviceBehaviors-->
          <serviceBehaviors>
            <behavior name="EnableMetadataBehaviors">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <!--添加serviceBehaviors:結束-->         

關於serviceMetadata的介紹,摘自msdn

此配置元素允許您控制服務的中繼資料發佈功能。為了防止無意中泄露潛在的敏感服務中繼資料,Windows Communication Foundation (WCF) 服務的預設配置將禁用中繼資料發佈。預設情況下此行為是安全的,但也意味著您無法使用中繼資料匯入工具(例如 Svcutil.exe)產生調用服務所需的用戶端代碼,除非在配置中顯式啟用服務的中繼資料發佈行為。使用此配置元素,可以為服務啟用此發布行為。

有關配置此行為的詳細程式碼範例,請參見Metadata Publishing Behavior。

利用可選的 httpGetBindinghttpsGetBinding 屬性,您可以配置用於通過 HTTP GET(或 HTTPS GET)檢索中繼資料的綁定。如果未指定這兩個屬性,則根據情況使用相應的預設綁定(採用 HTTP 時為 HttpTransportBindingElement,採用 HTTPS 時為 HttpsTransportBindingElement)進行中繼資料檢索。請注意:不能將這些屬性用於內建 WCF 綁定。僅支援具有支援 IReplyChannel 的內部繫結元素的綁定。此外,綁定的 MessageVersion 屬性必須為 None。

為了降低服務被惡意使用者濫用的可能性,可以使用 SSL over HTTP (HTTPS) 機制來確保傳輸的安全。為此,必須首先將一個適合的 X.509 憑證綁定到承載該服務的電腦上的特定連接埠。(有關更多資訊,請參見 Working with Certificates.)然後,將此元素添加到服務配置,並將 httpsGetEnabled 特性設定為 true。最後,將 httpsGetUrl 屬性設定為服務中繼資料終結點的 URL.

2.3為wcf添加webHttpBinding配置

   <!--添加bindings-->
      <bindings>
        <webHttpBinding>
          <binding name="test" crossDomainScriptAccessEnabled="true"></binding>
        </webHttpBinding>
      </bindings>
      <!--添加bindings:結束-->

注意要啟用跨網域設定:crossDomainScriptAccessEnabled="true"

2.4為service添加behaviorConfiguration配置資訊以及為endpoint添加bindingConfiguration跨網域設定資訊

  <!--為service添加:behaviorConfiguration:中繼資料-->
            <service name="Wcf.demo.AjaxService" behaviorConfiguration="EnableMetadataBehaviors">
              <!--為endpoint添加:bindingConfiguration跨域-->
                <endpoint address="" behaviorConfiguration="Wcf.demo.AjaxServiceAspNetAjaxBehavior"
                  bindingConfiguration="test"   binding="webHttpBinding" contract="Wcf.demo.AjaxService" />
            </service>
        </services>

至此服務端開發完畢。

三、用戶端開發

建立一個test.html頁面然後添加jquery類庫引用 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>,Demo中用的是jquery1.4.1min版本

貼一些html頁代碼很簡單,不做解釋了

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title>    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {                        $("#btnTest").bind("click", function () {                            var url = "http://localhost:7348/AjaxService.svc/Test?JsonCallBack=?&";                            $.getJSON(url, { "value": "小甜心,300站" }, function (msg) {                                alert(msg)                            });                        });                    });    </script></head><body><input  id="btnTest" value="Test" type="button"/></body></html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.