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、動態調用,示例代碼如下:
////// WebService代理類 /// public class WebServiceAgent { private object agent; private Type agentType; private const string CODE_NAMESPACE = "Beyondbit.WebServiceAgent.Dynamic"; //////調用指定的方法 /// ///方法名,大小寫敏感 ///參數,按照參數順序賦值 ///Web服務的返回值 public object Invoke(string methodName, params object[] args) { MethodInfo mi = agentType.GetMethod(methodName); return this.Invoke(mi, args); } //////調用指定方法 /// ///方法信息 ///參數,按照參數順序賦值 ///Web服務的返回值 public object Invoke(MethodInfo method, params object[] args) { return method.Invoke(agent, args); } public MethodInfo[] Methods { get { return agentType.GetMethods(); } } }