public class WebServiceClient { private object agent; private Type agentType; private const string CODE_NAMESPACE = "EnterpriseServerBase.WebService.DynamicWebCalling"; public WebServiceClient() { } public void ShowAllMethods() { MethodInfo[] pme = agentType.GetMethods(); int i = 0; while (i < pme.Length) { i++; } } public string GetOneMethod(string method) { MethodInfo pme = agentType.GetMethod(method); return pme.ToString(); } /// <summary< /// 构造函数 /// </summary< /// <param name="url"<</param< public void WebServiceInit(string url) { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(CODE_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.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 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()); } agentType = cr.CompiledAssembly.GetTypes()[0]; agent = Activator.CreateInstance(agentType); } ///<summary< ///调用指定的方法 ///</summary< ///<param name="methodName"<方法名,大小写敏感</param< ///<param name="args"<参数,按照参数顺序赋值</param< ///<returns<Web服务的返回值</returns< public object Invoke1(string methodName, params object[] args) { MethodInfo mi = agentType.GetMethod(methodName); return this.Invoke2(mi, args); } ///<summary< ///调用指定方法 ///</summary< ///<param name="method"<方法信息</param< ///<param name="args"<参数,按照参数顺序赋值</param< ///<returns<Web服务的返回值</returns< public object Invoke2(MethodInfo method, params object[] args) { return method.Invoke(agent, args); } public object WebServiceCall(string Function, object[] paramValue) { object actual = this.Invoke1(Function, paramValue); return actual; } }
创建一个全局的WebServiceClient实例,在适合的时候进行初始化提供服务器url,进行webService调用时不用重复请求url地址,速度上会有所提升