程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 動態調用WebService

C# 動態調用WebService

編輯:C#入門知識

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,接口名稱和參數即可實現動態調用。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved