[Wcf] 使用JQuery的Ajax方法來呼叫Wcf Service

  • 22990
  • 0

[Wcf] 使用JQuery Ajax來呼叫Wcf Service

 

前言

 

通常在Asp.Net中Client端呼叫Wcf服務時,

我們通常都會透過ScriptManager來註冊Service Reference,

就可以直接呼叫Wcf中的function了,

但今天如果不是使用Asp.Net的話,

我們也可以透過JQuery,來對Wcf進行呼叫。

 

實際演練

 

首先我們先建立一個允許Get或Post方法呼叫的Wcf Service,

建立Interface

using System.ServiceModel;
using System.ServiceModel.Web;

[ServiceContract]
public interface IHelloService
{
    [OperationContract]
    //if use "Post" to access wcf service
    [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    //if use "Get" to access wcf service
    //[WebGet(RequestFormat=WebMessageFormat.Json)]
    string SayHello(string name);
}

與平常不同的地方是,在OperationContract下多加了一個Attribute來標明這個方法允許使用Post呼叫

(若要使用Get,則需使用WebGet Attribute)

 

建立Wcf Service的Class

using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloService : IHelloService
{
    #region IHelloService Members

    public string SayHello(string name)
    {
        return string.Format("Hello, {0}" , name);
    }

    #endregion
}

在Service class上需要多加AspNetCompatibilityRequirements Attribute

再來需要更改web.config,將endpoint的binding指定為webHttpBinding,

並且增加endpoint的BehaviorConfiguration,來enableWebScript

<system.serviceModel>
		<services>
			<service name="HelloService" behaviorConfiguration="ServiceBehavior">
				<!-- Service Endpoints -->
				<endpoint address="" binding="webHttpBinding" contract="IHelloService" behaviorConfiguration="webBindingBehavior">					
					<identity>
						<dns value="localhost"/>
					</identity>
				</endpoint>
				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
			</service>
		</services>
		<behaviors>
			<serviceBehaviors>
				<behavior name="ServiceBehavior">
					<serviceMetadata httpGetEnabled="true"/>
					<serviceDebug includeExceptionDetailInFaults="false"/>
				</behavior>
			</serviceBehaviors>
			<endpointBehaviors>
				<behavior name="webBindingBehavior">
					<enableWebScript/>
				</behavior>
			</endpointBehaviors>
		</behaviors>
	</system.serviceModel>

如果設定都正確的話,我們可以正常的將Wcf Service成功的執行,並看到下面的畫面

2010-08-18_180255

接著我們可以來撰寫我們的網頁部分如下

使用JQuery的ajax方法來呼叫SayHello function

<!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>Using jquery to request wcf service</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        function Button_Click() {
            var name = $("#name").val();
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "http://localhost:1707/WCFService12/Service.svc/SayHello",
                //if use "GET" to access wcf service;
                //data: "name=" + name,
                data: '{"name":"' + name + '"}',
                processData: false,
                success: function(msg) {
                    alert(msg.d);
                },
                error: function(err) {
                    //error handling
                    alert("Error Occured!");
                }
            });
        }
    </script>

</head>
<body>
    <input type="text" id="name" />
    <input type="button" value="send!" onclick="javascript:Button_Click();return false;" />
</body>
</html>

 

執行之後,可以看到成功的呼叫Wcf Service

2010-08-18_181559

 

結語

 

如此一來,就算使用的不是Asp.Net,

我們還是一樣可以藉由Javascript來呼叫Wcf Service,

這也是選擇使用Web Service的好處之一囉!

如果有任何問題請跟我說,也歡迎大家多多指教 :)