---
title: "VS2010中使用Jquery调用Wcf服务读取数据库记录"
author: "xqf222"
date: "2013-07-28T13:28:00Z"
tags: []
slug: "vs2010-jquery-wcf"
draft: false
lastmod: "2013-08-05T15:54:37Z"
id: 1920263
url: "https://xqf222.iteye.com/blog/1920263"
---

VS2010中使用Jquery调用Wcf服务读取数据库记录

开发环境：Window Servere 2008 +SQL SERVE 2008 R2+ IIS7 +VS2010+Jquery1.3.2

功能实现： html中使用Jquery调用远程Wcf服务

优点总结：网上大部分的代码都是直接在web项目中包含SVC文件，也有的用ASPX页面来调用WCF服务，而不是HTML+Jquery+WCF+数据库模式的。

一、WCF服务调用数据库记录对应工程项目新建和代码  
打开VS2010，打开“文件”菜单，点击“新建项目”，在“添加新项目”窗体左侧选择项目类型为“WCF”,点击右侧“WCF服务库”,选择顶部的NET类型为" .NET Framework4" ，下方输入名称

为“Jquery.WcfService”

点击“全部保存”按钮，弹出保存项目对话框，名称为“Jquery.WcfService”位置“C:\\”,解决方案名称为“Jquery.Wcf”。

选择解决方案资源管理器中的“Jquery.WcfService”项目中的“Service1.cs”文件，点鼠右键，选择“重命名”，输入“CustomersService.cs”；

选择解决方案资源管理器中的“Jquery.WcfService”项目中的“IService1.cs”文件，按F2键，输入“ICustomersService.cs”；

选择解决方案资源管理器中的“Jquery.WcfService”项目,点鼠标右键，选择“属性”，设置“应用程序”-“目标框架”为“.NET Framework4”，弹出对话框中选择“是”。

选择解决方案资源管理器中的“Jquery.WcfService”项目,点鼠标右键，选择“添加引用”，在弹出的“添加引用”页面，选择“.NET”列表中“ System.ServiceModel.Web”项，点击“确定

”按钮。  
ICustomersService.cs代码文件如下：  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.ServiceModel;  
using System.ServiceModel.Web;

namespace Jquery.WcfService  
{  
// 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的接口名“ICustomersService”。  
\[ServiceContract]  
public interface ICustomersService  
{  
\[OperationContract]  
\[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]  
string GetCustomerByCustomerID(string CustomerID);  
}  
}

CustomersService.cs代码文件如下：

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Runtime.Serialization;  
using System.ServiceModel;  
using System.Text;  
using System.Data.SqlClient;  
using System.ServiceModel.Activation;

namespace Jquery.WcfService  
{  
// 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“CustomersService”。  
\[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
public class CustomersService : ICustomersService  
{  
public string GetCustomerByCustomerID(string CustomerID)  
{  
string strReturn = "";  
SqlConnection myConnection = new SqlConnection(@"Data Source=.\\N3;Initial Catalog=northwnd;User ID=sa;pwd=123456;");//这里修改为您的数据库连接字符串  
myConnection.Open();  
SqlCommand myCommand = myConnection.CreateCommand();  
myCommand.CommandText = "select * from Customers where CustomerID='" + CustomerID + "'";  
SqlDataReader myDataReader = myCommand.ExecuteReader();  
while (myDataReader.Read())  
{  
strReturn = string.Format("CustomerID:{0} ; CompanyName:{1} ; ContactName:{2} ", myDataReader\["CustomerID"], myDataReader\["CompanyName"],

myDataReader\["ContactName"]);  
}  
myDataReader.Close();  
myConnection.Close();  
return strReturn;  
}  
}  
}

App.config代码文件如下  
&lt;?xml version="1.0"?&gt;  
&lt;configuration&gt;

&lt;system.web&gt;  
&lt;compilation debug="true"/&gt;  
&lt;/system.web&gt;  
&lt;!-- 部署服务库项目时，必须将配置文件的内容添加到  
主机的 app.config 文件中。System.Configuration 不支持库的配置文件。--&gt;  
&lt;system.serviceModel&gt;

&lt;!-- A、服务配置 --&gt;  
&lt;services&gt;

&lt;service name="Jquery.WcfService.CustomersService" behaviorConfiguration="CustomerServiceBehavior"&gt;  
&lt;endpoint address="" binding="webHttpBinding" contract="Jquery.WcfService.ICustomersService" behaviorConfiguration="CustomersEndpointBehavior"&gt;  
&lt;identity&gt;  
&lt;dns value="localhost" /&gt;  
&lt;/identity&gt;  
&lt;/endpoint&gt;  
&lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt;  
&lt;host&gt;  
&lt;baseAddresses&gt;  
&lt;add baseAddress="[http://192.168.1.249:6089/Jquery.WcfService/CustomersService/](http://192.168.1.249:6089/Jquery.WcfService/CustomersService/)" /&gt;  
&lt;/baseAddresses&gt;  
&lt;/host&gt;  
&lt;/service&gt;

&lt;/services&gt;

&lt;!-- B、行为配置 --&gt;  
&lt;behaviors&gt;

&lt;!-- 1、配置服务对应的行为--&gt;  
&lt;serviceBehaviors&gt;

&lt;!-- 1.1发布到远程服务器对应的行为配置 --&gt;  
&lt;behavior name=""&gt;  
&lt;!-- 为避免泄漏元数据信息，  
请在部署前将以下值设置为 false 并删除上面的元数据终结点 --&gt;  
&lt;serviceMetadata httpGetEnabled="True"/&gt;  
&lt;!-- 要接收故障异常详细信息以进行调试，  
请将以下值设置为 true。在部署前设置为 false  
以避免泄漏异常信息--&gt;  
&lt;serviceDebug includeExceptionDetailInFaults="False"/&gt;  
&lt;useRequestHeadersForMetadataAddress&gt;  
&lt;defaultPorts&gt;  
&lt;add scheme="http" port="6089" /&gt;  
&lt;add scheme="https" port="6089" /&gt;  
&lt;/defaultPorts&gt;  
&lt;/useRequestHeadersForMetadataAddress&gt;  
&lt;/behavior&gt;

&lt;!-- 1.2服务对应的行为配置--&gt;  
&lt;behavior name="CustomerServiceBehavior"&gt;  
&lt;serviceMetadata httpGetEnabled="true" /&gt;  
&lt;serviceDebug includeExceptionDetailInFaults="false" /&gt;  
&lt;/behavior&gt;

&lt;/serviceBehaviors&gt;

&lt;!-- 2、添加终截节点对应的行为--&gt;  
&lt;endpointBehaviors&gt;  
&lt;behavior name="CustomersEndpointBehavior"&gt;  
&lt;webHttp/&gt;  
&lt;enableWebScript/&gt;  
&lt;/behavior&gt;  
&lt;/endpointBehaviors&gt;

&lt;/behaviors&gt;

&lt;!-- C、绑定配置 --&gt;  
&lt;bindings&gt;  
&lt;webHttpBinding&gt;  
&lt;!-- 跨域配置 --&gt;  
&lt;binding name="webBinding" crossDomainScriptAccessEnabled="true"&gt;&lt;/binding&gt;  
&lt;/webHttpBinding&gt;  
&lt;/bindings&gt;

&lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true"/&gt;

&lt;!-- 大数据传送设置 --&gt;  
&lt;standardEndpoints &gt;  
&lt;webHttpEndpoint &gt;  
&lt;standardEndpoint name="" maxReceivedMessageSize="3000000" defaultOutgoingResponseFormat="Json" helpEnabled="true" automaticFormatSelectionEnabled="true"&gt;  
&lt;readerQuotas maxArrayLength="300000"/&gt;  
&lt;/standardEndpoint&gt;  
&lt;/webHttpEndpoint&gt;  
&lt;/standardEndpoints&gt;

&lt;/system.serviceModel&gt;

&lt;startup&gt;&lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/&gt;&lt;/startup&gt;&lt;/configuration&gt;

二、WCF服务对应测试项目新建

点击VS2010开发环境中的“文件”菜单，点击“新建项目”，添加新项目，类型为“测试”，名称为“Jquery.WcfTest”;解决方案类型为“添加到解决方案”。

选中Jquery.WcfTest项目的UnitTest1.cs文件, 点鼠标右键--选择“删除”。

选中Jquery.WcfTest项目，点鼠标右键，点“添加”，点“单元测试”，在弹出的“创建单元测试”窗体中，展开“Jquery.WcfService”项目目录树，勾

选“Jquery.WcfService.CustomersService”项，点击“确定”按钮；  
双击打开Jquery.WcfTest项目中的“CustomersServiceTest.cs”文件，修改“GetCustomerByCustomerIDTest()”方法中的string CustomerID = string.Empty;为string CustomerID =

"ALFKI";  
运行测试：点击VS2010开发环境中的“测试”菜单-点“运行”-“当前上下文中的测试”。

提示信息为如下：  
未通过GetCustomerByCustomerIDTestJquery.WcfTestAssert.AreEqual 失败。应为: &lt;&gt;，实际为: &lt;CustomerID:ALFKI ; CompanyName:Alfreds Futterkiste ; ContactName:Maria

Anders &gt;。  
证明WCF服务已经连接到数据库并能正确调用出数据库中对应的记录了。

三、用于发布WCF服务的IIS站点新建和WCF服务的发布操作步骤  
新建一个站点目录C:\\6089  
打开IIS,找到网站节点，新建一个站点:网站名称为6089;物理路径为C:\\6089;端口为6089;  
打开应用程序池节点，选中6089应用程序池，双击打开编辑应用程序池设置，修改托管管道模式为"经典";设置.NET Framework版本为.NET Framework v4.0.30319.

回到VS2010开发环境中，选中Jquery.WcfService项目，点鼠标右键，选中“发布(B)”；打开发布WCF服务窗体，在目标位置输入"[http://localhost:6089](http://localhost:6089)"，点确定按钮。

回到IIS中，选择名称为“6089”的网站，点右侧下方的“内容视图”，在右侧中间点鼠标右键-“刷新”，会显示出最新的“Jquery.WcfService.CustomersService.svc”等文件，选

择“Jquery.WcfService.CustomersService.svc”文件，点鼠标右键--“浏览”，会在浏览器中打开“http://localhost:6089/Jquery.WcfService.CustomersService.svc”。正常的话，会显

示“已创建服务。”等信息。

四、新建Web站点和HTML页面，测试 Jquery调用WCF服务中的方法  
点击VS2010开发环境中的“文件”菜单，点击“新建项目”，选择项目类型为“Web”,点击右侧“ASP.NET 空Web应用程序”，输入名称为“Jquery.Web”，解决方案类型为“添加到解决方案

”。

选中Jquery.Web项目，点鼠标右键，选中“添加”-“新建项”，选择项目类型为“Web”,点击右侧"HTML页"，下方输入名称为“index.htm”，点击“添加”按钮。

选中Jquery.Web项目，点鼠标右键，选中“添加”-“新建文件夹”，重命名文件夹为"js"。

浏览器中打开[http://code.google.com/p/jqueryjs/downloads/list](http://code.google.com/p/jqueryjs/downloads/list)网址，下载jquery-1.3.2.js文件到本地，并复制粘贴到Jquery.Web项目中的js文件夹

移动鼠标选中Jquery.Web项目中的"index.htm"页面，点鼠标右键--“设为起始页”。  
index.html代码如下：  
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd](http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd)"&gt;  
&lt;html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)"&gt;  
&lt;head&gt;  
&lt;title&gt;Jquery调用Wcf服务获取数据库记录&lt;/title&gt;  
&lt;script type="text/javascript" src="js/jquery-1.3.2.js"&gt;&lt;/script&gt;  
&lt;script language="javascript" type="text/javascript"&gt;  
function getCustomerInfo() {  
var sendData = '{"CustomerID":"' + document.getElementById('CustomerID').value + '"}';  
alert(sendData);  
$.ajax({  
type: 'post',  
url: 'http://localhost:6089/Jquery.WcfService.CustomersService.svc/GetCustomerByCustomerID',  
contentType: 'text/json',  
data: sendData,  
success: function (msg) {  
var obj = eval('(' + msg + ')');  
alert(obj.d);  
}  
});  
}  
&lt;/script&gt;  
&lt;/head&gt;  
&lt;body&gt;  
&lt;form id="form1" runat="server"&gt;  
&lt;div&gt;  
CustomerID：&lt;input type="text" id="CustomerID" value="ALFKI" /&gt;  
&lt;br /&gt;  
CompanyName：&lt;label id="CompanyName" /&gt;  
&lt;br /&gt;  
ContactName：&lt;label id="ContactName" /&gt;  
&lt;br /&gt;  
&lt;input type="button" value="获取数据库信息" onclick="getCustomerInfo();" /&gt;  
&lt;/div&gt;  
&lt;/form&gt;  
&lt;/body&gt;  
&lt;/html&gt;

按F5运行，在浏览器中会打开“http://localhost:1767/index.htm”页面，点击“获取数据库信息”按钮，会提示Jquery的发送信息和来自WCF服务的返回数据库记录信息字符串。

项目代码下载地址：[http://download.csdn.net/detail/xqf222/5828217](http://download.csdn.net/detail/xqf222/5828217)