使用WebService的方式调用部署在服务器的Wcf服务

本文阐述如何使用WebService的方式调用部署在服务器的Wcf服务

1、创建Wcf服务库项目:

2、修改默认的绑定方式为basicHttpBinding:


3、Service1类为如下代码:

// 注意: 如果更改此处的接口名称“IService1”,也必须更新 App.config 中对“IService1”的引用。
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

// 任务: 在此处添加服务操作
}

// 使用下面示例中说明的数据协定将复合类型添加到服务操作
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";

[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}

 


4、我们就用默认代码演示功能,编译后发布:


5、创建客户端项目MonikerClient:


6、 添加部署在服务器的前端代理类及其配置文件,在IIS浏览.svc文件,按页面说明的方法操作:

VS2008的命令提示窗(C:\Program Files\Microsoft Visual Studio 9.0\VC)下执行: svcutil.exe http://chris.hissoft.com/WCFServiceMoniker/WcfServiceMoniker.Service1.svc?wsdl

得到文件Service1.svcoutput.config(改名app.config后加如工程):


7、添加两个按钮到窗体,并给第1个按钮订阅单击事件,需要增加引用程序集:


 

private void button1_Click(object sender, EventArgs e)
{
Service1Client client
= new Service1Client();

// 使用 "client" 变量在服务上调用操作。
MessageBox.Show(client.GetData(1345));

// 始终关闭客户端。
client.Close();
}

 

8、运行后得到正确的结果:

 

9、下面继续让我们用WebService调用方式实现(注意前面中间层Wc服务如果不是用basicHttpBinding配置的则不能用WebService调用):


10、点击“添加Web引用”按钮:Url为http://localhost/WCFServiceMoniker/WcfServiceMoniker.Service1.svc,点击“前往”即可得到如下信息,Web引用名改为:WebService:


11、然后点击“添加引用”按钮,解决方案资源管理器就得到如下结果:


12、给第2个按钮增加单击事件,代码如下(注意GetData方法参数多了一个bool valueSpecified,该参数需要设置为true才能返回正确结果):

private void button2_Click(object sender, EventArgs e)
{
WebService.Service1 ws
= new MonikerClient.WebService.Service1();

//参数xxxSpecified需要置为true(如果置为false,则返回0-错误)。
MessageBox.Show(ws.GetData(333, true));

ws.Dispose();
}


13、运行,并点击第2个按钮得到正确的结果:

 

 

 

 

 

posted @ 2010-06-24 09:57  Chr☆s  阅读(6241)  评论(6编辑  收藏  举报