动态调用Web服务
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Web; using System.Web.Services.Description; using System.CodeDom; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; namespace Yom.Framework.Core { public class WebService { public static object InvokeWebService(string url, string methodName, object[] args) { return InvokeWebService(url, null, methodName, args); } public static object InvokeWebService(string url, string className, string methodName, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if (string.IsNullOrEmpty(className)) { className = GetWsClassName(url); } try { WebClient wc = new WebClient(); Stream stream = wc.OpenRead(string.Format("{0}?WSDL", url)); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, string.Empty, string.Empty); CodeNamespace cn = new CodeNamespace(@namespace); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider icc = new CSharpCodeProvider(); CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.AddRange(new string[] { "System.dll", "System.Xml.dll", "System.Web.Services.dll", "System.Data.dll" }); CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (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(string.Format("{0}.{1}", @namespace, className), true, true); object obj = Activator.CreateInstance(t); MethodInfo mi = t.GetMethod(methodName); return mi.Invoke(obj, args); } catch (Exception ex) { throw ex; } } static string GetWsClassName(string wsURL) { string[] parts = wsURL.Split(‘/‘); return parts[parts.Length - 1].Split(‘.‘)[0]; } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。