如何动态调用WebServices

我们都知道,调用WS可以在工程中添加对WS的WEB引用。
但是,如果我们不想通过添加引用的方式,而是在代码中动态引用该怎么办呢?
首先,我们该想到WS的实现也是一个类的形式。
其次,WS在传输过程中是通过WSDL来进行描述的(使用SOAP协议)。
因此,我们需要获取WS的WSDL描述,并通过该描述来动态生成程序集。
最后:通过反射来获取新生成的程序集,并调用其方法!
上述步骤需要引用如下四个名称空间:
using  System.Web.Services.Description;  //WS的描述
//以下几个用于根据描述动态生成代码并动态编译获取程序集
using  System.CodeDom; 
using  Microsoft.CSharp;
using  System.CodeDom.Compiler;
上述几个名称空间中包括如下几个重要的类:
using  System.Web.Services.Description下:
ServiceDescription  //WS描述
ServiceDescriptionImporter  //通过描述生成客户端代理类,特别注意其中的Style
以下是MSDN对其的描述:
        XML Web services 的接口通常由 Web 服务描述语言 (WSDL) 文件来说明。例如,若要获取有关使用 http://localhost/service.asmx 处公开的 ASP.NET 的 Web 服务的 WSDL 说明,只需导航到 http://localhost/service.asmx?WSDL。使用 ServiceDescriptionImporter 类可以方便地将 WSDL 说明中包含的信息导入到 <?XML:NAMESPACE PREFIX = MSHelp NS = "http://msdn.microsoft.com/mshelp" /> 对象。通过调整 Style 参数的值,可以指示 ServiceDescriptionImporter 实例生成客户端代理类(通过透明调用该类可提供 Web 服务的功能)或生成抽象类(该类封装 Web 服务的功能而不实现该功能)。如果将 Style 属性设置为 Client,则 ServiceDescriptionImporter 生成客户端代理类,通过调用这些类来提供说明的 Web 服务的功能。如果将 Style 属性设置为 ,则 ServiceDescriptionImporter 实例生成抽象类,这些类表示所说明的 XML Web services 的功能而不进行实现。然后,可以通过编写从这些抽象类继承的类来对其进行实现,并实现相关的方法。
using  System.CodeDom下:
 CodedomUnit //它用于设定动态代码的名称空间,类名等,可以通过ServiceDescriptionImporter.Import()方法将WS的描述代码写入该类,以作动态编译用

using System.CodeDom.Compiler下:
CodedomProvider //用于创建和检索代码生成器和代码编译器的实例,我们主要用到其实现子类CShareCodeProvider
可以直接用CShareCodeProvider provider=new CShareCodeProvider()来生成,或者用CodedomProvider.CreateProvider("CSharp")来生成
ICodeCompiler //用于编译基于 System.CodeDom 的源代码表示形式。
它通过CodedomProvider的CreateCompiler()方法来
CompilerResults  //表示从编译器返回的编译结果。 它由ICodeCompiler根据指定的编译器设置从指定的 CodeCompileUnit 所包含的 System.CodeDom 树中编译程序集并返回。CompiledAssembly 属性指示编译的程序集。

了解如上信息后,就可动态调用WS了。
如下是摘自http://www.cnblogs.com/ruochen/archive/2007/12/11/990427.html的代码演示:

ContractedBlock.gif ExpandedBlockStart.gif Code
 1None.gifusing System;
 2None.gifusing System.Collections.Generic;
 3None.gifusing System.Text;
 4None.gifusing System.Net;
 5None.gifusing System.IO;
 6None.gifusing System.Web.Services.Description;
 7None.gifusing System.CodeDom;
 8None.gifusing Microsoft.CSharp;
 9None.gifusing System.CodeDom.Compiler;
10None.gif
11None.gifnamespace TestSkin
12ExpandedBlockStart.gifContractedBlock.gifdot.gif{
13InBlock.gif    class Webservices
14ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
15ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
16InBlock.gif        /// 实例化WebServices
17InBlock.gif        /// </summary>
18InBlock.gif        /// <param name="url">WebServices地址</param>
19InBlock.gif        /// <param name="methodname">调用的方法</param>
20ExpandedSubBlockEnd.gif        /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>

21InBlock.gif        public static object InvokeWebService(string url, string methodname, object[] args)
22ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
23InBlock.gif
24InBlock.gif            //这里的namespace是需引用的webservices的命名空间,在这里是写死的,大家可以加一个参数从外面传进来。
25InBlock.gif            string @namespace = "client";
26InBlock.gif            try
27ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
28InBlock.gif                //获取WSDL
29InBlock.gif                WebClient wc = new WebClient();
30InBlock.gif                Stream stream = wc.OpenRead(url + "?WSDL");
31InBlock.gif                ServiceDescription sd = ServiceDescription.Read(stream);
32InBlock.gif                string classname = sd.Services[0].Name;
33InBlock.gif                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
34InBlock.gif                sdi.AddServiceDescription(sd, """");
35InBlock.gif                CodeNamespace cn = new CodeNamespace(@namespace);
36InBlock.gif
37InBlock.gif                //生成客户端代理类代码
38InBlock.gif                CodeCompileUnit ccu = new CodeCompileUnit();
39InBlock.gif                ccu.Namespaces.Add(cn);
40InBlock.gif                sdi.Import(cn, ccu);
41InBlock.gif                CSharpCodeProvider csc = new CSharpCodeProvider();
42InBlock.gif                ICodeCompiler icc = csc.CreateCompiler();
43InBlock.gif
44InBlock.gif                //设定编译参数
45InBlock.gif                CompilerParameters cplist = new CompilerParameters();
46InBlock.gif                cplist.GenerateExecutable = false;
47InBlock.gif                cplist.GenerateInMemory = true;
48InBlock.gif                cplist.ReferencedAssemblies.Add("System.dll");
49InBlock.gif                cplist.ReferencedAssemblies.Add("System.XML.dll");
50InBlock.gif                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
51InBlock.gif                cplist.ReferencedAssemblies.Add("System.Data.dll");
52InBlock.gif
53InBlock.gif                //编译代理类
54InBlock.gif                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
55InBlock.gif                if (true == cr.Errors.HasErrors)
56ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
57InBlock.gif                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
58InBlock.gif                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
59ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
60InBlock.gif                        sb.Append(ce.ToString());
61InBlock.gif                        sb.Append(System.Environment.NewLine);
62ExpandedSubBlockEnd.gif                    }

63InBlock.gif                    throw new Exception(sb.ToString());
64ExpandedSubBlockEnd.gif                }

65InBlock.gif
66InBlock.gif                //生成代理实例,并调用方法
67InBlock.gif                System.Reflection.Assembly assembly = cr.CompiledAssembly;
68InBlock.gif                Type t = assembly.GetType(@namespace + "." + classname, truetrue);
69InBlock.gif                object obj = Activator.CreateInstance(t);
70InBlock.gif                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
71InBlock.gif
72InBlock.gif                return mi.Invoke(obj, args);
73ExpandedSubBlockEnd.gif            }

74InBlock.gif            catch
75ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
76InBlock.gif                return null;
77ExpandedSubBlockEnd.gif            }

78ExpandedSubBlockEnd.gif        }

79ExpandedSubBlockEnd.gif    }

80ExpandedBlockEnd.gif}



===了解上述类和方法后,基本就可以动态调用WS了。
特别注意的是:动态编译后需要用到反射来读取并执行。因此需要您了解什么是反射及如何反射

转载于:https://www.cnblogs.com/McJeremy/archive/2008/11/10/1330463.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值