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

2023-01-07,,,,

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代码文件如下
<?xml version="1.0"?>
<configuration>

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

<!-- A、服务配置 -->
    <services>

<service name="Jquery.WcfService.CustomersService" behaviorConfiguration="CustomerServiceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="Jquery.WcfService.ICustomersService" behaviorConfiguration="CustomersEndpointBehavior">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://192.168.1.249:6089/Jquery.WcfService/CustomersService/" />
          </baseAddresses>
        </host>
      </service>
     
    </services>

<!-- B、行为配置 -->
    <behaviors>
     
      <!-- 1、配置服务对应的行为-->
      <serviceBehaviors>

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

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

</serviceBehaviors>

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

</behaviors>

<!-- C、绑定配置 -->
    <bindings>
      <webHttpBinding>
        <!-- 跨域配置 -->
        <binding name="webBinding" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>
   
    <serviceHostingEnvironment  aspNetCompatibilityEnabled="true"/>

<!-- 大数据传送设置 -->
    <standardEndpoints >
      <webHttpEndpoint >
        <standardEndpoint   name="" maxReceivedMessageSize="3000000" defaultOutgoingResponseFormat="Json" helpEnabled="true"  automaticFormatSelectionEnabled="true">
          <readerQuotas maxArrayLength="300000"/>
        </standardEndpoint>
      </webHttpEndpoint>
    </standardEndpoints>
   
  </system.serviceModel>

<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

二、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开发环境中的“测试”菜单-点“运行”-“当前上下文中的测试”。

提示信息为如下:
未通过 GetCustomerByCustomerIDTest Jquery.WcfTest Assert.AreEqual 失败。应为: <>,实际为: <CustomerID:ALFKI ; CompanyName:Alfreds Futterkiste ; ContactName:Maria

Anders   >。 
证明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",点确定按钮。

回到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网址,下载jquery-1.3.2.js文件到本地,并复制粘贴到Jquery.Web项目中的js文件夹

移动鼠标选中Jquery.Web项目中的"index.htm"页面,点鼠标右键--“设为起始页”。
index.html代码如下:
<!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>Jquery调用Wcf服务获取数据库记录</title>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script language="javascript" type="text/javascript">
        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);
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    CustomerID:<input type="text" id="CustomerID" value="ALFKI" />
    <br />
    CompanyName:<label id="CompanyName" />
    <br />
    ContactName:<label id="ContactName" />
    <br />
    <input type="button"  value="获取数据库信息" onclick="getCustomerInfo();" />
    </div>
    </form>
</body>
</html>

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

项目代码下载地址:http://download.csdn.net/detail/xqf222/5828217

VS2010中使用Jquery调用Wcf服务读取数据库记录的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。