ASP.NET應(yīng)用程序的WCF服務(wù)
ASP.NET應(yīng)用程序添加WCF服務(wù)
現(xiàn)在,我們來學(xué)習(xí)如何在前面的ASP.NET網(wǎng)站中添加一個支持AJAX功能的WCF服務(wù)。為此,請右擊上面的示例網(wǎng)站AJAXWCFTest1并選擇“Add New Items…”,在隨后出現(xiàn)的“Add New Items”對話框中選擇“AJAX-Enabled WCF Service”模板添加一個新的WCF服務(wù)并命名為TimeService。
通過上面的操作后,你會發(fā)現(xiàn)Web網(wǎng)站中添加了一個服務(wù)端點(即timeservice.svc)以及與之相聯(lián)系的位于文件夾App_Code下的 Code-behind文件timeservice.cs。此外,還注意到,配置文件web.config也被修改以便為剛剛創(chuàng)建的WCF服務(wù)提供相應(yīng)的注冊和發(fā)現(xiàn)信息。
現(xiàn)在創(chuàng)建的這個TimeService類中已經(jīng)隱含地描述了所定義WCF服務(wù)的契約及其顯式實現(xiàn)。注意,其中的ServiceContract和OperationContract屬性承擔(dān)了與以前的WCF版本編程中同樣的角色。另外,為了簡化起見,在此沒有使用接口定義契約。
- using System;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Activation;
- using System.ServiceModel.Web;
- [ServiceContract (Namespace = "Samples.Services")]
- [AspNetCompatibilityRequirements(
- RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
- public class TimeService
- ...{
- [OperationContract]
- public DateTime GetTime()
- ...{
- return DateTime.Now;
- }
- [OperationContract]
- public string GetTimeFormat(string format)
- ...{
- return DateTime.Now.ToString(format);
- }
- }
注意到,上面的TimeService類共暴露了兩個公共端點,分別是GetTime和GetTimeFormat。
到達(dá)上面接口中方法的端點定義于一個SVC文件中。下面給出了文件timeservice.svc的內(nèi)容:
- <%@ ServiceHost Language="C#"
- Debug="true"
- Service="TimeService"
- CodeBehind="~/App_Code/TimeService.cs" %>
這個服務(wù)宿主(ServiceHost)指明了實現(xiàn)該服務(wù)使用的語言以及相應(yīng)的源文件的位置,***通過Service屬性標(biāo)識所使用的契約名字。
在正式開始測試這個服務(wù)前還有***一項工作就是在宿主ASP.NET應(yīng)用程序的配置文件web.config中注冊上面這個WCF服務(wù)。下面展示了配置文件web.config中的相關(guān)配置節(jié)的內(nèi)容:
- <system.serviceModel>
- <behaviors>
- <endpointBehaviors>
- <behavior name="TimeServiceAspNetAjaxBehavior">
- <enableWebScript />
- </behavior>
- </endpointBehaviors>
- </behaviors>
- <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
- <services>
- <service name="TimeService">
- <endpoint address=""
- behaviorConfiguration="TimeServiceAspNetAjaxBehavior"
- binding="webHttpBinding"
- contract="TimeService" />
- </service>
- </services>
- </system.serviceModel>
注意,上面的配置內(nèi)容是隨著WCF服務(wù)的創(chuàng)建由系統(tǒng)自動生成的。
在此,首先針對前面WCF服務(wù)中的所有端點注冊一個行為列表。通過這種方式,為WCF服務(wù)TimeServiceAspNetAjaxBehavior定義了一個行為并且指出它使用客戶端腳本經(jīng)由HTTP Web協(xié)議接受請求。從邏輯上分析,上面的enableWebScript元素與ASP.NET Web服務(wù)中用于修飾Web服務(wù)類的ScriptService屬性是一致的。
然后,需要枚舉宿主于當(dāng)前ASP.NET應(yīng)用程序中的所有WCF服務(wù)。注意,上面的web.config文件中僅展示了一個名字為TimeService的服務(wù),它的一個端點使用了TimeService契約和webHttpBinding綁定模型。
【編輯推薦】