這段時間一直在“研究”(不太好意思用這個詞)WCFService,覺得挺好玩的。下面把一個用JavaScript調用WCFService的執行個體分享給大家。
註:為貪圖省事,WCFService與調用者均在一個網站項目裡。HostService方式也採用了最普通的IIS承載。
1、建立一個介面,用於條件約束服務提供的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
// NOTE: If you change the interface name "IAjaxWCFService" here, you must also update the reference to "IAjaxWCFService" in Web.config.
[ServiceContract(Namespace = "SampleAjaxService")]
public interface IAjaxWCFService
{
[OperationContract]
[WebGet]
string GetMessage();//簡單返回提示資訊
}
2、建立一個類,實現上述介面
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
public class AjaxWCFService : IAjaxWCFService
{
#region IAjaxWCFService Members
public string GetMessage()
{
return "Hello,welcome to wcf Service!";
}
#endregion
}
到此為目ServiceClass算是做好了,剩下的就是:承載Service。
3、建立AjaxWCFService.svc 檔案
檔案內容<%@ ServiceHost Language="C#" Debug="true" Service="AjaxWCFService" CodeBehind="~/App_Code/AjaxWCFService.cs" %>
4、配置Service
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="ajaxServiceBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="AjaxWCFService">
<endpoint address="" behaviorConfiguration="ajaxServiceBehavior"
binding="webHttpBinding" contract="IAjaxWCFService" />
</service>
</services>
</system.serviceModel>
配置時注意:高亮顯示部分
到此為止服務也算是承載起來了,可以在瀏覽器中查看一下效果。(先慶祝一下)
4、添加 .aspx頁面調用已經搭建好的WCF Service
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple AJAX Service Client Page</title>
<script type="text/javascript">
// This function creates an asynchronous call to the service
function Call(operation) {
// Instantiate a service proxy
var proxy = new SampleAjaxService.IAjaxWCFService();
proxy.GetMessage(onSuccess, onFail, null);
}
// This function is called when the result from the service call is received
function onSuccess(mathResult) {
document.getElementById("divMessage").innerText = mathResult;
}
// This function is called if the service call fails
function onFail() {
document.getElementById("divMessage").innerText = "Error";
}
</script>
</head>
<body>
<h1>
Simple AJAX Service Client Page</h1>
<br />
<br />
<input id="btnGetMessage" type="button" onclick="return Call();" value="GetMessage" />
<br />
Result:
<div id="divMessage" style="color: Red;">
</div>
<form id="mathForm" action="" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="AjaxWCFService.svc" />
</Services>
</asp:ScriptManager>
</form>
</body>
</html>
5、運行頁面,查看效果。
如果得到以下效果,你就成功了。
運行結果
Result:
Hello,welcome to wcf Service!