首页 > 学院 > 开发设计 > 正文

C# WebService调用方法

2019-11-17 03:14:20
字体:
来源:转载
供稿:网友

C# WebService调用方法

public class WebServiceHelper { /// < summary> /// 动态调用web服务 /// < /summary> /// < param name="methodname">方法名< /param> /// < param name="args">参数< /param> /// < returns>< /returns> public static object InvokeWebService(string methodname, object[] args) { string url = "http://localhost:8080/myWebService.asmx"; string @namespace = "myWebService";//命名空间 string classname = WebServiceHelper.GetWsClassName(url);//"myWebService"; try { //获取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(@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()); } //生成代理实例,并调用方法 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); // PropertyInfo propertyInfo = type.GetProperty(propertyname); //return propertyInfo.GetValue(obj, null); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } } private static string GetWsClassName(string wsUrl) { string[] parts = wsUrl.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); return pps[0]; }

}

//调用webservice示例:

/// <summary> /// 用户登录验证 /// </summary> /// <param name="username">用户名</param> /// <param name="pwd">密码</param> /// <param name="userid">用户id</param> /// <param name="error">接口异常信息</param> /// <returns>登录成功返回true</returns> public bool Login(string username, string pwd, out string userid, out string error) { object[] obj = new object[] { username, pwd,null, null }; bool res = (bool)WebServiceHelper.InvokeWebService("Login", obj); userid = (string)obj[2]; error = (string)obj[3]; return res; }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表