jQuery ajax调用WCF服务实例
恩,在由瘦客户端转换成胖浏览器端的“潮流”下,必然要使用JavaScript调用后台的各种服务。
屌丝所维护的产品通信都是使用的WCF服务,因此必然要学习这样的内容。借用jQuery强大的库,使用JavaScript访问WCF服务非常简便。同事研究了一个breeze库,那么屌丝就来试验一下ajax。这里把实现简单地记录以便马克一下,以后忘了就看这篇日志来作弊。
一、更改WCF服务的配置
默认情况下,WCF服务是不允许使用HTTP请求来访问的。我们需要将WCF服务的配置文件(注意如果有其他启动WCF服务的项目应该修改该项目的app.config文件)修改,将serviceHostEnvironment节添加aspNetCompatibilityEnabled属性并设为true:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<serviceActivations>
<add relativeAddress="TableManager.svc" service="TableManagerIntegrationTestService.TestResultService"
factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>
</serviceActivations>
</serviceHostingEnvironment>
而且,与之相关的服务binding属性要配置成webHttpBinding,这样js才能进行调用:
<service name="TableManagerIntegrationTestService.TestResultService">
<endpoint address="" binding="webHttpBinding" contract="TableManagerIntegrationTestService.ITestResultService" behaviorConfiguration="EndpBehavior">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
......
二、WCF服务的操作契约
S要调用的服务操作契约必须为WebGet或WebInvoke。标记为WebGet属性的可以使用HTTP GET方法调用,而WebInvoke标记允许HTTP POST方法调用。
我这里有一个简单的例子,该WCF服务接收年月日作为参数,返回该天的日志记录。
该服务的Service Contract定义如下:
[ServiceContract]
public interface ITestResultService
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
List<TestResultData> GetData(int year, int month, int date);
}
GetData方法的标记定义了该方法允许HTTP POST方法调用,返回的数据是JSON格式。指定了数据的返回格式后,我们不需要编写任何代码,WCF会将一个可序列化的对象自动转换成对应的格式。
在服务类中,还需要指定AspNetComatibilityRequirements标记,如下面的示例代码所示:
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class TestResultService : ITestResultService
{
public List<TestResultData> GetData(int year, int month, int date)
{
try
{
DateTime start_time = new DateTime(year, month, date, 0, 0, 0);
DateTime end_time = new DateTime(year, month, date, 23, 59, 59);
DataSet ds = LogDataAccess.SelectDailyBuildLog(start_time, end_time);
var test_result_list = new List<TestResultData>();