这不是一篇教你了解WebService的博文,也不是对WebService的深刻理解, 这是一篇教你在开发过程当中,若是动态的调用WebService一个方法.web
1 public partial class Component1 : Component 2 { 3 public Component1() 4 { 5 InitializeComponent(); 6 } 7 8 public Component1(IContainer container) 9 { 10 container .Add(this ); 11 12 InitializeComponent(); 13 } 14 }
1 [ WebServiceBinding (Namespace = "http://tempuri.org/" )] 2 public class Component1 : SoapHttpClientProtocol 3 { 4 public Component1() 5 { 6 InitializeComponent(); 7 } 8 9 public Component1(IContainer container) 10 { 11 container . Add(this ); 12 13 InitializeComponent(); 14 } 15 }
SoapHttpClientProtocol SoapHttpClientProtocol类能够直接访问指定的webService的指定方法若要与 XML Web services 通讯,请为要调用的 XML Web services 建立一个间接或直接从 WebClientProtocol 派生的代理类。 能够不用手动建立代理类,而使用 Web 服务描述语言工具 (Wsdl.exe) 为给定 XML Web services 的服务说明建立代理类。 当为 SOAP 协议生成代理类时,对 XML Web services 方法的同步调用经过 Invoke 方法进行,而异步调用经过 BeginInvoke 方法和 EndInvoke 方法进行。
1 <add key="ServiceAddress" value="http://localhost:7340/CourseMakerService.asmx" />
在咱们添加的Conponent Class 构造中调用服务器连接地址服务器
1 public Component1( string serviceUrl) 2 { 3 if (serviceUrl. Equals( "UpdateServiceAddress" )) 4 base .Url = ConfigurationManager . AppSettings["UpdateServiceAddress" ]; 5 else 6 base .Url = ConfigurationManager . AppSettings["ServiceAddress" ]; 7 }
而后当咱们想要调用WebService中的方法时,只须要在Component1类中写. 若是个人调用方式异步
1 [ WebServiceBinding(Namespace = "http://tempuri.org/" )] 2 public class OffLineLearingClient : SoapHttpClientProtocol 3 { 4 public OffLineLearingClient( string serviceUrl) 5 { 6 if (serviceUrl. Equals( "UpdateServiceAddress" )) 7 base .Url = ConfigurationManager . AppSettings["UpdateServiceAddress" ]; 8 else 9 base .Url = ConfigurationManager . AppSettings["ServiceAddress" ]; 10 } 11 public OffLineLearingClient() 12 { 13 base .Url = ConfigurationManager . AppSettings["ServiceAddress" ]; 14 } 15 [ SoapDocumentMethod ] 16 public YHBJUser GetUser( YHBJUser user) 17 { 18 return base . Invoke("GetUser" , new object [] { user })[0 ] as YHBJUser ; 19 } 20 21 [ SoapDocumentMethod ] 22 public List < YHBJClass> GetTrainings11( string userId) 23 { 24 return base . Invoke("GetTrainings11" , new object [] { userId })[0 ] as List <YHBJClass > ; 25 }
这样咱们就能够动态的实现若是调用WebService了.工具