C#调用WebService的方式有很多:
1、直接在项目中添加WebService引用,这种方式比较简单,但不是动态的,即每次服务地址或者内容变了之后都要重新添加引用。
2、使用SoapHttpClientProtocol,这种方式需要把添加WebService引用生成的Reference.cs类中服务接口,集成进自己定义的服务调用类中,服务调用类继承自SoapHttpClientProtocol,如果服务接口发生了改变,需要修改服务调用类。示例代码如下:
public class MySoapHttpClientProtocol : SoapHttpClientProtocol { public MySoapHttpClientProtocol(string url) { Url = url; } [SoapHeader("ClientContext")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace = MyNamespace, ResponseNamespace = MyNamespace, Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlElementAttribute("out", IsNullable = true)] public string myMethod([System.Xml.Serialization.XmlElementAttribute(IsNullable = true)] string in0) { try { object[] results = this.Invoke("getConnection", new object[] { in0 }); return ((string)(results[0])); } catch (Exception ex) { } } }
其中myMethod是从服务引用的Reference.cs中拷贝过来的,当然你也可以自己写,拷贝过来更简单。
3、动态调用,示例代码如下:
/// <summary> /// WebService代理类 /// </summary> public class WebServiceAgent { private object agent; private Type agentType; private const string CODE_NAMESPACE = "Beyondbit.WebServiceAgent.Dynamic"; /// <summary< /// 构造函数 /// </summary< /// <param name="url"<</param< public WebServiceAgent(string url) { XmlTextReader reader = new XmlTextReader(url);// + "?wsdl"); //创建和格式化 WSDL 文档 ServiceDescription sd = ServiceDescription.Read(reader); //创建客户端代理代理类 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, null, null); //使用 CodeDom 编译客户端代理类 CodeNamespace cn = new CodeNamespace(CODE_NAMESPACE); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider icc = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu); agentType = cr.CompiledAssembly.GetTypes()[0]; agent = Activator.CreateInstance(agentType); } ///<summary> ///调用指定的方法 ///</summary> ///<param name="methodName">方法名,大小写敏感</param> ///<param name="args">参数,按照参数顺序赋值</param> ///<returns>Web服务的返回值</returns> public object Invoke(string methodName, params object[] args) { MethodInfo mi = agentType.GetMethod(methodName); return this.Invoke(mi, args); } ///<summary> ///调用指定方法 ///</summary> ///<param name="method">方法信息</param> ///<param name="args">参数,按照参数顺序赋值</param> ///<returns>Web服务的返回值</returns> public object Invoke(MethodInfo method, params object[] args) { return method.Invoke(agent, args); } public MethodInfo[] Methods { get { return agentType.GetMethods(); } } }
调用时只需要指定,服务的URL,接口名称和参数即可实现动态调用。