一、方法InvokeWebservice
/// <summary>
/// 根據指定的信息,調用遠程WebService方法
/// </summary>
/// <param name="url">WebService的http形式的地址</param>
/// <param name="namespace">欲調用的WebService的命名空間</param>
/// <param name="classname">欲調用的WebService的類名(不包括命名空間前綴)</param>
/// <param name="methodname">欲調用的WebService的方法名</param>
/// <param name="args">參數列表</param>
/// <returns>WebService的執行結果</returns>
/// <remarks>
/// 如果調用失敗,將會拋出Exception。請調用的時候,適當截獲異常。
/// 異常信息可能會發生在兩個地方:
/// 1、動態構造WebService的時候,CompileAssembly失敗。
/// 2、WebService本身執行失敗。
/// </remarks>
/// <example>
/// <code>
/// object obj = InvokeWebservice("http://localhost/GSP_WorkflowWebservice/common.asmx","Genersoft.Platform.Service.Workflow","Common","GetToolType",new object[]{"1"});
/// </code>
/// </example>
public static object InvokeWebservice(string url, string @namespace, string classname, string methodname, object[] args)
{
try
{
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.Stream stream = wc.OpenRead(url + "?WSDL");
System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream);
System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace);
System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler();
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.CompilerResults cr = icc.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(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
二、調用
object[] Object = new object[] { "Sun" };//定義object數組
object aa = InvokeWebservice("http://192.168.1.200:111", "WebService2", "Service1", "show", Object);
textBox1.Text = aa.ToString();