C#动态调用Web服务的3种方法

来源:百度文库 编辑:神马文学网 时间:2024/04/28 04:14:24
  • C#动态调用Web服务的3种方法

  • http://developer.51cto.com  2009-08-18 13:22  greatandforever  博客园  我要评论(1)
    本文列出了如何在C#下动态调用Web服务的3种方法,供大家参考。

    我们在开发C# WinForm时,有时会调用Web服务,服务是本地的当前好办,只要在Project中的Web References中引入就可以在代码中直接创建一个Web服务对象来引用,其实其原理是C#帮你自动创建客户端代理类的方式调用WebService,但如果调用的服务是动态的,比如说在几个IIS中都有相同的一个服务,在运行时输入具体的IP才确定调用哪个服务,那要怎么样实现呢。

    C#动态调用Web服务方法一: 手动的添加一个Web引用,然后修改下本地的代理类。最后实现Web Service的URI部署到配置文件里。 具体做法如下:

    以下代码是显示如何配置动态的Web Service,以服务单元C(类名为Web_SVSGC)为例:

    (1)首先在Web引用中的本地代理类中添加一个构造函数,这个构造函数是以Web Service的URL为参数的重载方法。

    复制  保存

            
    1. Namespace Web_SVSGC  
    2.     '< remarks/> 
    3.     < System.Diagnostics.DebuggerStepThroughAttribute(),  _     System.ComponentModel.DesignerCategoryAttribute("code"),  _     System.Web.Services.WebServiceBindingAttribute(Name:="SVSGCSoap", [Namespace]:="http://tempuri.org/QYJSERVICE/SVSGC"),  _     System.Xml.Serialization.XmlIncludeAttribute(GetType(Attribute))>  _  
    4.     Public Class SVSGC  
    5.         Inherits System.Web.Services.Protocols.SoapHttpClientProtocol  
    6.     '< remarks/> 
    7.         Public Sub New()  
    8.             MyBase.New  
    9.             Me.Url = "http://localhost/QYJSERVICE/WEBSERVICE/SERVICE/SVSGC.asmx" 
    10.         End Sub  
    11.  
    12.         '添加一个带参数的构造函数。  
    13.         Public Sub New(ByVal strUrl As String)   
    14.             MyBase.New()   
    15.             Me.Url = strUrl   
    16.         End Sub  
    17.  

    (2)将Web Service的url配置在调用Web Service的应用程序的配置文件中。(其中的value可以随时修改。)

    复制  保存

            
    1. < configuration> 
    2.     < appSettings> 
    3.               < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" /> 
    4.     < /appSettings> 
    5. < /configuration>< configuration> 
    6.     < appSettings> 
    7.               < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" /> 
    8.     < /appSettings> 
    9. < /configuration> 

    (3)调用时,根据配置文件的Url动态的生成Web Service。

    复制  保存       

            
    1. '要调用的Web Service的URL  
    2.         Dim strWebSvsUrl As String  
    3.         '声明一个要调用的Web Service  
    4.         Dim objSVSGC As WebSvs_GC. SVSGC  
    5.         '调用Web Service的远程方法的返回值  
    6.         Dim strReturnValue As String  
    7.         Try  
    8.             '从配置文件中取得Web Service的URL  
    9.             strWebSvsUrl = _   
    10.             System.Configuration.ConfigurationSettings.AppSettings("SVSGC_URL")   
    11.             '生成一个Web Service实例  
    12.             objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)  
    13.             '调用这个Web Service里的远程方法  
    14.             strReturnValue = objSVSGC.HelloWorld()  
    15.         Catch ex As Exception  
    16.         End Try 

    C#动态调用Web服务方法二:完全动态处理,传入服务服务网址,方法名和参数即可.

            
    1. using System;   
    2. using System.Net;   
    3. using System.IO;   
    4. using System.CodeDom;   
    5. using Microsoft.CSharp;   
    6. using System.CodeDom.Compiler;   
    7. using System.Web.Services.Description;   
    8. using System.Web.Services.Protocols;   
    9.  
    10. namespace HB.Common   
    11. {   
    12.     /* 调用方式   
    13.      *   string url = "http://www.webservicex.net/globalweather.asmx" ;   
    14.      *   string[] args = new string[2] ;   
    15.      *   args[0] = "Hangzhou";   
    16.      *   args[1] = "China" ;   
    17.      *   object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;   
    18.      *   Response.Write(result.ToString());   
    19.      */   
    20.     public class WebServiceHelper   
    21.     {   
    22.         #region InvokeWebService   
    23.         /// < summary>   
    24.         /// 动态调用web服务   
    25.         /// < /summary>   
    26.         /// < param name="url">WSDL服务地址< /param>   
    27.         /// < param name="methodname">方法名< /param>   
    28.         /// < param name="args">参数< /param>   
    29.         /// < returns>< /returns>   
    30.         public static object InvokeWebService(string url, string methodname, object[] args)   
    31.         {   
    32.             return WebServiceHelper.InvokeWebService(url, null, methodname, args);   
    33.         }   
    34.  
    35.         /// < summary>   
    36.         /// 动态调用web服务   
    37.         /// < /summary>   
    38.         /// < param name="url">WSDL服务地址< /param>   
    39.         /// < param name="classname">类名< /param>   
    40.         /// < param name="methodname">方法名< /param>   
    41.         /// < param name="args">参数< /param>   
    42.         /// < returns>< /returns>   
    43.         public static object InvokeWebService(string url, string classname, string methodname, object[] args)   
    44.         {   
    45.             string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";   
    46.             if ((classname == null) || (classname == ""))   
    47.             {   
    48.                 classname = WebServiceHelper.GetWsClassName(url);   
    49.             }   
    50.  
    51.             try   
    52.             {   
    53.                 //获取WSDL   
    54.                 WebClient wc = new WebClient();   
    55.                 Stream stream = wc.OpenRead(url + "?WSDL");   
    56.                 ServiceDescription sd = ServiceDescription.Read(stream);   
    57.                 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();   
    58.                 sdi.AddServiceDescription(sd, """");   
    59.                 CodeNamespace cn = new CodeNamespace(@namespace);   
    60.  
    61.                 //生成客户端代理类代码   
    62.                 CodeCompileUnit ccu = new CodeCompileUnit();   
    63.                 ccu.Namespaces.Add(cn);   
    64.                 sdi.Import(cn, ccu);   
    65.                 CSharpCodeProvider icc = new CSharpCodeProvider();   
    66.  
    67.                 //设定编译参数   
    68.                 CompilerParameters cplist = new CompilerParameters();   
    69.                 cplist.GenerateExecutable = false;   
    70.                 cplist.GenerateInMemory = true;   
    71.                 cplist.ReferencedAssemblies.Add("System.dll");   
    72.                 cplist.ReferencedAssemblies.Add("System.XML.dll");   
    73.                 cplist.ReferencedAssemblies.Add("System.Web.Services.dll");   
    74.                 cplist.ReferencedAssemblies.Add("System.Data.dll");   
    75.  
    76.                 //编译代理类   
    77.                 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);   
    78.                 if (true == cr.Errors.HasErrors)   
    79.                 {   
    80.                     System.Text.StringBuilder sb = new System.Text.StringBuilder();   
    81.                     foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)   
    82.                     {   
    83.                         sb.Append(ce.ToString());   
    84.                         sb.Append(System.Environment.NewLine);   
    85.                     }   
    86.                     throw new Exception(sb.ToString());   
    87.                 }   
    88.  
    89.                 //生成代理实例,并调用方法   
    90.                 System.Reflection.Assembly assembly = cr.CompiledAssembly;   
    91.                 Type t = assembly.GetType(@namespace + "." + classname, truetrue);   
    92.                 object obj = Activator.CreateInstance(t);   
    93.                 System.Reflection.MethodInfo mi = t.GetMethod(methodname);   
    94.  
    95.                 return mi.Invoke(obj, args);   
    96.  
    97.                 /*   
    98.                 PropertyInfo propertyInfo = type.GetProperty(propertyname);   
    99.                 return propertyInfo.GetValue(obj, null);   
    100.                 */   
    101.             }   
    102.             catch (Exception ex)   
    103.             {   
    104.                 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));   
    105.             }   
    106.         }   
    107.  
    108.         private static string GetWsClassName(string wsUrl)   
    109.         {   
    110.             string[] parts = wsUrl.Split('/');   
    111.             string[] pps = parts[parts.Length - 1].Split('.');   
    112.  
    113.             return pps[0];   
    114.         }   
    115.         #endregion   
    116.     }   

    返回时如果不是字符串,即强制转换,如返回是DataSet,则

            
    1. string url = "http://www.webservicex.net/globalweather.asmx" ;   
    2. string[] args = new string[2] ;   
    3. args[0] = "Hangzhou";   
    4. args[1] = "China" ;   
    5. object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;   
    6. DataSet DSRe=(DataSet)result;  

    C#动态调用Web服务方法三:URL Behavior 属性

     

    如果知道服务的方法和参数,只是调用的URL网址会随时变化,那么可以手工创建一个服务,添加上对应的的方法和传入参数,然后引入到项目中,就可以直接开发,在创建服务的实例化时,才修改对应的URL即可.

    例如服务中有个方法叫GetTax,那么就可以这样改:

            
    1. GetTax.GetTax GetTax1 = new GetTax.GetTax();   
    2. GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx";        //动态引入服务器   
    3.                    
    4. DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa);   //调用服务器返回开票数据