1. 在visual studio安装目录下找到 Visual Studio Tools
2. 以管理员身份运行 “VS2013 x64 兼容工具命令提示” (如果安装的32位VS,运行 x86的)
3. 执行命令(在服务地址后加上 ?wsdl):svcutil.exe http://localhost:8091/PatientService.svc?wsdl
4. 可以看到生成了两个文件
5. 根据目录找到这个文件,将.cs文件拷贝到项目中
6. 新建WcfChannelFactory类
1 public static class WcfChannelFactory 2 { 3 #region WCF服务工厂 4 public static T CreateServiceByUrl<T>(string url) 5 { 6 return CreateServiceByUrl<T>(url, "basicHttpBinding"); 7 } 8 9 public static T CreateServiceByUrl<T>(string url, string bing) 10 { 11 try 12 { 13 if (string.IsNullOrEmpty(url)) throw new NotSupportedException("This url is not Null or Empty!"); 14 EndpointAddress address = new EndpointAddress(url); 15 Binding binding = CreateBinding(bing); 16 ChannelFactory<T> factory = new ChannelFactory<T>(binding, address); 17 return factory.CreateChannel(); 18 } 19 catch (Exception ex) 20 { 21 throw new Exception("创建服务工厂出现异常."); 22 } 23 } 24 #endregion 25 26 #region 创建传输协议 27 /// <summary> 28 /// 创建传输协议 29 /// </summary> 30 /// <param name="binding">传输协议名称</param> 31 /// <returns></returns> 32 private static Binding CreateBinding(string binding) 33 { 34 Binding bindinginstance = null; 35 if (binding.ToLower() == "basichttpbinding") 36 { 37 BasicHttpBinding ws = new BasicHttpBinding(); 38 ws.MaxBufferSize = 2147483647; 39 ws.MaxBufferPoolSize = 2147483647; 40 ws.MaxReceivedMessageSize = 2147483647; 41 ws.ReaderQuotas.MaxStringContentLength = 2147483647; 42 ws.CloseTimeout = new TimeSpan(0, 30, 0); 43 ws.OpenTimeout = new TimeSpan(0, 30, 0); 44 ws.ReceiveTimeout = new TimeSpan(0, 30, 0); 45 ws.SendTimeout = new TimeSpan(0, 30, 0); 46 47 bindinginstance = ws; 48 } 49 else if (binding.ToLower() == "nettcpbinding") 50 { 51 NetTcpBinding ws = new NetTcpBinding(); 52 ws.MaxReceivedMessageSize = 65535000; 53 ws.Security.Mode = SecurityMode.None; 54 bindinginstance = ws; 55 } 56 else if (binding.ToLower() == "wshttpbinding") 57 { 58 WSHttpBinding ws = new WSHttpBinding(SecurityMode.None); 59 ws.MaxReceivedMessageSize = 65535000; 60 ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows; 61 ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows; 62 bindinginstance = ws; 63 } 64 return bindinginstance; 65 66 } 67 #endregion 68 }
7. 用法:
string url = "http://localhost:9090/PatientService.svc";//WebConfig.WCFServiceUrl; IPatientService proxy = WcfChannelFactory.CreateServiceByUrl<IPatientService>(url); string getdata = proxy.GetData(123);
IPatientService为自动生成的cs文件中的接口,其中包含了wcf服务中的方法
时间: 2024-11-13 10:02:34