C# 调用WCF服务

 1 using System;
 2 using System.Reflection;
 3 using System.ServiceModel;
 4 using System.ServiceModel.Channels;
 5 
 6 namespace ManageSystem.Common {
 7     public class WCFChannelFactory {
 8         /// <summary>
 9         /// 执行方法   WSHttpBinding
10         /// </summary>
11         /// <typeparam name="T">服务接口</typeparam>
12         /// <param name="uri">wcf地址</param>
13         /// <param name="methodName">方法名</param>
14         /// <param name="args">参数列表</param>
15         public static object ExecuteMethod<T>(string uri, string methodName, params object[] args) {
16             BasicHttpBinding binding = new BasicHttpBinding();
17             EndpointAddress endpoint = new EndpointAddress(uri);
18 
19             using (ChannelFactory<T> channelFactory = new ChannelFactory<T>(binding, endpoint)) {
20                 T instance = channelFactory.CreateChannel();
21                 using (instance as IDisposable) {
22                     try {
23                         Type type = typeof(T);
24                         MethodInfo mi = type.GetMethod(methodName);
25                         return mi.Invoke(instance, args);
26                     }
27                     catch (TimeoutException) {
28                         //(instance as ICommunicationObject).Abort();
29                         //throw;
30                     }
31                     catch (CommunicationException) {
32                         //(instance as ICommunicationObject).Abort();
33                         //throw;
34                     }
35                     catch (Exception) {
36                         //(instance as ICommunicationObject).Abort();
37                         //throw;
38                     }
39                 }
40             }
41             return null;
42         }
43    }
44 }

 

posted @ 2013-12-03 17:50  zhuhc  阅读(783)  评论(0编辑  收藏  举报