WCF 客户端调用服务操作的两种方法
生活随笔
收集整理的這篇文章主要介紹了
WCF 客户端调用服务操作的两种方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本節的主要內容:1、通過代理類的方式調用服務操作。2、通過通道的方式調用服務操作。3、代碼下載
一、通過代理類的方式調用服務操作(兩種方式添加代理類)
1.手動編寫代理類,如下:
客戶端契約:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ServiceModel; 7 namespace y.WcfFirst.Client.Proxys 8 { 9 [ServiceContract] 10 public interface IHello 11 { 12 [OperationContract] 13 string Say(string name); 14 } 15 } View Code客戶端代理類:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ServiceModel; 7 using System.ServiceModel.Channels; 8 namespace y.WcfFirst.Client.Proxys 9 { 10 public class HelloProxy:ClientBase<IHello>,IHello 11 { 12 public HelloProxy() 13 : base() 14 { 15 } 16 17 public string Say(string name) 18 { 19 return base.Channel.Say(name); 20 } 21 } 22 } View Code客戶端app.config文件:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <system.serviceModel> 4 <client> 5 <endpoint name="wcfFirst" 6 address="net.tcp://localhost:6666/hello" 7 binding="netTcpBinding" 8 contract="y.WcfFirst.Client.Proxys.IHello"></endpoint> 9 </client> 10 </system.serviceModel> 11 </configuration> View Code客戶端的調用:
1 using (HelloProxy proxy = new HelloProxy()) 2 { 3 Console.WriteLine("Recevie from Server:{0}", proxy.Say(name)); 4 proxy.Close(); 5 } View Code2.通過Metadata方式產生代理類。
服務端需要對app.config進行配置如下:
客戶端的操作步驟:先運行服務端(host)。
a.在客戶端點擊Add Service Reference按鈕,添加Service引用。如下圖:
b.輸入Address地址:http://localhost:8888,點擊"GO",獲取服務操作。并且重命名Namespace,如下圖:
c.客戶端對代理類的調用。
1 using (HelloClient clientProxy = new HelloClient()) 2 { 3 Console.WriteLine("Recevie from Server:{0}", clientProxy.Say(name)); 4 clientProxy.Close(); 5 } View Code二、通過通道方式調用服務操作
1.客戶端契約,如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ServiceModel; 7 namespace y.WcfFirst.ClientChannel.Proxy 8 { 9 [ServiceContract] 10 public interface IHello 11 { 12 [OperationContract] 13 string Say(string name); 14 } 15 } View Code2.客戶端配置文件的設置:如下:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <system.serviceModel> 4 <client> 5 <endpoint name="wcfFirst" 6 address="net.tcp://localhost:6666/hello" 7 binding="netTcpBinding" 8 contract="y.WcfFirst.ClientChannel.Proxy.IHello"></endpoint> 9 </client> 10 </system.serviceModel> 11 </configuration> View Code3.客戶端調用服務操作:如下:
1 ChannelFactory<IHello> factory = new ChannelFactory<IHello>("wcfFirst"); 2 IHello channelProxy = factory.CreateChannel(); 3 using(channelProxy as IDisposable) 4 { 5 Console.WriteLine("Recevie from Server:{0}", channelProxy.Say(name)); 6 } View Code?
demo
轉載于:https://www.cnblogs.com/liuxiaoji/p/4538584.html
總結
以上是生活随笔為你收集整理的WCF 客户端调用服务操作的两种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 训练赛题解
- 下一篇: 索引键的唯一性(3/4):唯一聚集索引上