动态调用web服务,该方法只针对Web service, WCF的服务不行,如果是WCF的就通过工具直接生产代理类,把代理类配置到调用的项目中,通过配置客户端的终结点动态的取实现:
通过Svcutil.exe 工具生成代理类调用
1.找到如下地址“C:\Windows\System32\cmd.exe” 命令行工具,右键以管理员身份运行(视系统是否为win7 而定)
2.输入如下命令:"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcUtil.exe" /out:C:\WCFClint\ClientCode.cs /config:C:\WCFClint\app.config http://localhost:81/WCFServiceTest/CNPatentSearchService.svc
说明:
参数1: “C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcUtil.exe” ,是指 SvcUtil.exe 工具的地址
参数2: “C:\WCFClint\ClientCode.cs ” ,是指生成的代理类输出存放到的地址
参数3: “C:\WCFClint\app.config ” ,是指存放到调用WCF服务程序目录下的配置文件的输出存放地址
参数4: “http://localhost:81/WCFServiceTest/CNPatentSearchService.svc” ,是指部署到IIS 的WCF服务的地址
/// <summary>
/// 动态调用webservice
/// </summary>
public static class WebServiceHelper
{
public static object InvokeWebService(string url, string methodname, params object[] args)
{
return InvokeWebService(url, null, methodname, args);
}
public static object InvokeWebService(string url, string classname, string methodname, params object[] args)
{
string @namespace = "ServiceBase.WebService.DynamicWebLoad";
if (string.IsNullOrEmpty(classname))
{
classname = WebServiceHelper.GetClassName(url);
}
//获取服务描述语言(WSDL)
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace);
//生成客户端代码类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
//CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
CodeDomProvider provider = new CSharpCodeProvider();
//设定编译器的参数
CompilerParameters cplist = new CompilerParameters();
cplist.GenerateExecutable = false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
//编译代理类
CompilerResults cr = provider.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new StringBuilder();
foreach (CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString() + System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
// 生成代理实例并调用方法
Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
}
private static string GetClassName(string url)
{
string[] parts = url.Split('/');
string[] pps = parts[parts.Length - 1].Split('.');
return pps[0];
}
}