C# 动态调用webservice代码

/// <summary>
/// 动态调用WebService
/// </summary>
/// <param name="url">URL</param>
/// <param name="nameSpace">命名空间名称</param>
/// <param name="className">类名</param>
/// <param name="conStructorArgs">构造函数参数</param>
/// <param name="methodName">方法名</param>
/// <param name="methodArgs">调用方法参数</param>
public object InvokeWebService(string url, string nameSpace, string className, string methodName, object[] methodArgs)
{
using (WebClient wc = new WebClient())
{
using (Stream stream = wc.OpenRead(url + "?WSDL"))
{
//获取WSDL描述
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
//导入命名空间
CodeNamespace nmspace = new CodeNamespace(nameSpace);
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add(nmspace);

ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
if (warning == 0)
{
//获取编译器
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//准备参数
CompilerParameters paras = new CompilerParameters();
paras.GenerateExecutable = false;
paras.GenerateInMemory = false;
paras.ReferencedAssemblies.Add("System.dll");
paras.ReferencedAssemblies.Add("System.XML.dll");
paras.ReferencedAssemblies.Add("System.Web.Services.dll");
paras.ReferencedAssemblies.Add("System.Data.dll");
//动态编译
CompilerResults result = provider.CompileAssemblyFromDom(paras, new CodeCompileUnit[] { unit });
//获取编译来的程序集
Assembly asb = result.CompiledAssembly;
//反射创建实例,调用方法
Type type = asb.GetType(nameSpace + "." + className);
object obj = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod(methodName);
return method.Invoke(obj, methodArgs);
}
return null;
}
}
}

posted @ 2017-02-13 09:16  chyun2011  阅读(213)  评论(0编辑  收藏  举报