C# 动态调用WebService

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();
            }
        }
    }

调用时只需要指定,服务的URL,接口名称和参数即可实现动态调用。

你可能感兴趣的:(C#)