1. 程式人生 > 其它 >動態呼叫Webservice介面

動態呼叫Webservice介面

/// <summary>
/// 呼叫WebService
/// </summary>
/// <param name="wsUrl">WebService地址</param>
/// <param name="className">類名</param>
/// <param name="methodName">方法名稱</param>
/// <param name="args">引數列表</param>
/// <returns></returns>
public static object InvokeWebService(string wsUrl, string className, string methodName, object[] args)
{
var @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if (string.IsNullOrEmpty(className)) className = GetWsClassName(wsUrl);
//獲取WSDL
var wc = new WebClient();
var stream = wc.OpenRead(wsUrl + "?wsdl");
var sd = ServiceDescription.Read(stream);
var sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
var cn = new CodeNamespace(@namespace);
//生成客戶端代理類程式碼
var ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
var csc = new CSharpCodeProvider();
var icc = csc.CreateCompiler();
//設定編譯引數
var 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");
//編譯代理類
var cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (cr.Errors.HasErrors)
{
var sb = new StringBuilder();
foreach (CompilerError ce in cr.Errors)
{
sb.Append(ce);
sb.Append(Environment.NewLine);
}

throw new Exception(sb.ToString());
}

//生成代理例項,並呼叫方法
var assembly = cr.CompiledAssembly;
var t = assembly.GetType(@namespace + "." + className, true, true);
var obj = Activator.CreateInstance(t);
var mi = t.GetMethod(methodName);
return mi.Invoke(obj, args);
}