WCF入门实例(ZT)
2019/7/7 1
WCF服务用于两个不同项目中的调用,在这里我举例项目A调用WCF服务实现查询数据功能。
第一步:创建数据库,有点数据能展示出来就行。
-
Create database SalesLibrary --创建库
-
Create table SalesVolume --创建表
-
-
-
-
-
第二步:创建存储过程(可以没有此步,只是方便查询)。
-
create proc proc_ShowSalesVolume
-
-
select * from dbo.SalesVolume
第三步:创建一个WCF解决方案。
删除掉默认的Iservice1和Service1,创建自己的WCF服务名称。
第四步:编写WCF服务。
在IsalesVolumeOperation接口中写一个现实数据的方法ShowSalesVolume,一定要写上[OperationContract],如若不写外界无法对其进行调用。
-
-
using System.Collections.Generic;
-
-
using System.Runtime.Serialization;
-
using System.ServiceModel;
-
-
-
-
-
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“ISalesVolumeOperation”。
-
[ServiceContract] // 服务合同 即提供服务的接口或类
-
public interface ISalesVolumeOperation
-
-
[OperationContract] //服务契约 即提供服务的实现方法
-
DataTable ShowSalesVolume();
-
-
在salesVolumeOperation中完善查询的的过程以及需要返回的参数。
-
-
using System.Collections.Generic;
-
-
using System.Runtime.Serialization;
-
using System.ServiceModel;
-
-
-
using System.Data.SqlClient;
-
-
-
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“SalesVolumeOperation”。
-
// 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 SalesVolumeOperation.svc 或 SalesVolumeOperation.svc.cs,然后开始调试。
-
public class SalesVolumeOperation : ISalesVolumeOperation
-
-
public DataTable ShowSalesVolume()
-
-
DataSet ds = new DataSet();
-
SqlConnection con = new SqlConnection("data source=.;initial catalog=SalesLibrary;user id=sa;password=sa123");
-
string sql = "proc_ShowSalesVolume"; //存储过程名称
-
using (SqlCommand cmd = new SqlCommand(sql, con))
-
-
-
cmd.CommandType = CommandType.StoredProcedure;
-
SqlDataAdapter da = new SqlDataAdapter(cmd);
-
-
-
-
-
-
第五步:对WCF服务接口测试看看是否无误。
选中SalesVolumeOperation.svc右键在浏览器中查看,然后复制其路径。
打开测试工具SoapUI,将路径复制到initial WSDL 然后在路径结尾写上?wsdl。
接着开始进行测试:
看来WCF服务没有出现问题,那么我们就开始创建第二个程序来访问这个WCF服务。
第六步:创建ASP.NET Web 应用程序(和WCF不在同一个解决方案)。
选择空版本就行,然后右键服务-->添加服务引用-->高级-->添加web引用:
然后在解决方案中就可以看到:
第七步:实现调用WCF服务。
新建一个页面用于展示数据,名为ShowData.aspx
前台代码:
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
-
-
-
<form id="form1" runat="server">
-
-
<asp:Repeater ID="Repeater1" runat="server">
-
-
-
-
-
-
-
-
-
-
-
后台代码:
-
-
using System.Collections.Generic;
-
-
-
-
using System.Web.UI.WebControls;
-
-
-
-
public partial class ShowData : System.Web.UI.Page
-
-
protected void Page_Load(object sender, EventArgs e)
-
-
-
-
-
-
-
private void GetSalesVolume()
-
-
SalesVolumeOperation.SalesVolumeOperation sa = new SalesVolumeOperation.SalesVolumeOperation(); //实例化WCF接口
-
DataTable dt = sa.ShowSalesVolume(); //接口下的方法
-
List<SalesVolume> list = new List<SalesVolume>();
-
-
foreach(DataRow dr in dt.Rows)
-
-
-
sv.Id = Convert.ToInt32(dr["Id"]);
-
sv.Num = Convert.ToInt32(dr["Num"]);
-
sv.Product = dr["Product"].ToString();
-
-
-
Repeater1.DataSource = list;
-
-
-
-
-
-
public int Id { get; set; }
-
public int Num { get; set; }
-
public string Product { get; set; }
-
-