如何建立一個AJAX-Enabled WCF Service

 

原創地址:http://www.cnblogs.com/jfzhu/p/4041638.htmljavascript

轉載請註明出處html

 

前面的文章中介紹過《Step by Step 建立一個WCF Service 》以及《如何使用WCF的Trace與Message Log功能》,本文介紹如何建立一個AJAX-Enabled WCF Service。java

(一)建立一個WCF AJAX-enabled service

1. 打開Visual Studio 2012,建立一個ASP.NET Empty Web Application Project,命名爲SandwichServices。這時Visual Studio的web.config文件內容爲:web

 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
</configuration>

 

2. 添加一個AJAX-enabled WCF Service,命名爲CostService.svc瀏覽器

 

using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
        
    }
}


由於咱們不打算使用TCP等HTTP以外的Protocol,因此設置爲AspNetCompatibilityEnabled。工具

 

3. 修改Namespace ServiceContractAttribute,並添加一個CostOfSandwiches方法post

 

using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SandwichServices
{
    [ServiceContract(Namespace = "SandwichServices")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CostService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

        [OperationContract]
        public double CostOfSandwiches(int quantity)
        {
            return 1.25 * quantity;
        }
    }
}

 

4. 這時Visual Studio生成的web.config文件ui

 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SandwichServices.CostService">
        <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="SandwichServices.CostService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

 

若是在瀏覽器中訪問CostService.svc,獲得以下錯誤spa

Untitled

 

 

5. 修改web.config文件debug

 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="SandwichServices.CostServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="SandwichServices.CostServiceServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="SandwichServices.CostService" behaviorConfiguration="SandwichServices.CostServiceServiceBehavior">
        <endpoint address="" behaviorConfiguration="SandwichServices.CostServiceAspNetAjaxBehavior"
            binding="webHttpBinding" contract="SandwichServices.CostService" />
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

 

再次在瀏覽器中打開CostService.svc,能夠正常訪問了。

image

 

(二)建立Client端,調用WCF Service

1. 建立一個aspx Page

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebClient.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        function Button1_onclick() {
            var service = new SandwichServices.CostService();
            service.CostOfSandwiches(3, onSuccess, null, null);
        }

        function onSuccess(result) {
            alert(result);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
        <input id="Button1" type="button" value="Price for 3 Sandwiches" onclick="return Button1_onclick()" />
        </p>
    </div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="http://192.168.6.47:8080/CostService.svc" />
            </Services>
        </asp:ScriptManager>
    </form>
</body>
</html>

 

2. 在瀏覽器中打開該頁面,而後用F12工具能夠看到加載進來的JavaScript,是WCF Service生成的。

image

 

Fiddler

image

 

3. 點擊按鈕調用WCF Service

image

image

 

(三) 總結

WCF Service的配置文件中的endpoint的binding要使用webHttpBinding,endpointBehavior要設置成enableWebScript。

WebForm中要在ScriptManager中添加WCF Service的引用。

相關文章
相關標籤/搜索