C#如何动态调用Web服务

来源:互联网 发布:ssd硬盘检测软件 编辑:程序博客网 时间:2024/05/21 11:25

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


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

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

(1)首先在Web引用中的本地代理类中添加一个构造函数,这个构造函数是以Web Service的URL为参数的重载方法。 
复制  保存Namespace Web_SVSGC
    '<remarks/>
    <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))>  _
    Public Class SVSGC
        Inherits System.Web.Services.Protocols.SoapHttpClientProtocol
    '<remarks/>
        Public Sub New()
            MyBase.New
            Me.Url = "http://localhost/QYJSERVICE/WEBSERVICE/SERVICE/SVSGC.asmx"
        End Sub

        '添加一个带参数的构造函数。
        Public Sub New(ByVal strUrl As String) 
            MyBase.New() 
            Me.Url = strUrl 
        End Sub

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

复制  保存<configuration>
    <appSettings>
              <add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" />
    </appSettings>
</configuration><configuration>
    <appSettings>
              <add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" />
    </appSettings>
</configuration>

(3)调用时,根据配置文件的Url动态的生成Web Service。 
复制  保存'要调用的Web Service的URL
        Dim strWebSvsUrl As String
        '声明一个要调用的Web Service
        Dim objSVSGC As WebSvs_GC. SVSGC
        '调用Web Service的远程方法的返回值
        Dim strReturnValue As String
        Try
            '从配置文件中取得Web Service的URL
            strWebSvsUrl = _ 
            System.Configuration.ConfigurationSettings.AppSettings("SVSGC_URL") 
            '生成一个Web Service实例
            objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)
            '调用这个Web Service里的远程方法
            strReturnValue = objSVSGC.HelloWorld()
        Catch ex As Exception
        End Try


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

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

返回时如果不是字符串,即强制转换,如返回是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;

方法三: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);   //调用服务器返回开票数据

 

0 0