晨小猿
Hello Word.

          

/// <summary>
/// 动态调用web服务
/// </summary>
/// <param name="url">url</param>
/// <param name="methodname">方法</param>
/// <param name="args">参数</param>
/// <returns>object基类对象</returns>
public static object InvokeWebService(string url, string methodname, object[] args)
{
object result = null;
if (string.IsNullOrWhiteSpace(url))
return result;
try
{
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.Stream stream = wc.OpenRead(url);

System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
string className = sd.Services[0].Name;
System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace("");
System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);

System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.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");

System.CodeDom.Compiler.CodeDomProvider provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
System.CodeDom.Compiler.CompilerResults cr = provider.CompileAssemblyFromDom(cplist, ccu);

if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(className, true, true);

object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
result = mi.Invoke(obj, args);
}
catch (Exception ex)
{
result = null;
System.Windows.Forms.MessageBox.Show(ex.Message + " " + ex.StackTrace);
}
return result;
}

posted on 2020-12-15 10:04  晨小猿  阅读(271)  评论(0编辑  收藏  举报