1 /// <summary>
2 /// 动态调用webservice
3 /// </summary>
4 /// <param name="url"></param>
5 /// <param name="methodName"></param>
6 /// <param name="args"></param>
7 /// <returns></returns>
8 public static object InvokeWebService(string url, string methodName, object[] args)
9 {
10 //这里的namespace是需引用的webservices的命名空间
11 string @namespace = "WebServerClient";
12 try
13 {
14 //获取WSDL
15 WebClient webClient = new WebClient();
16 Stream stream = webClient.OpenRead(url + "?WSDL");
17 ServiceDescription serviceDescription = ServiceDescription.Read(stream);
18 string classname = serviceDescription.Services[0].Name;
19 ServiceDescriptionImporter serviceDescriptionImporter = new ServiceDescriptionImporter();
20 serviceDescriptionImporter.AddServiceDescription(serviceDescription, null, null);
21 CodeNamespace cn = new CodeNamespace(@namespace);
22
23 //生成客户端代理类代码
24 CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
25 codeCompileUnit.Namespaces.Add(cn);
26 serviceDescriptionImporter.Import(cn, codeCompileUnit);
27 CSharpCodeProvider csc = new CSharpCodeProvider();
28
29 //设定编译参数
30 CompilerParameters compilerParameters = new CompilerParameters();
31 compilerParameters.GenerateExecutable = false;
32 compilerParameters.GenerateInMemory = true;
33 compilerParameters.ReferencedAssemblies.Add("System.dll");
34 compilerParameters.ReferencedAssemblies.Add("System.XML.dll");
35 compilerParameters.ReferencedAssemblies.Add("System.Data.dll");
36 compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
37
38 //编译代理类
39 CompilerResults compilerResults = csc.CompileAssemblyFromDom(compilerParameters, codeCompileUnit);
40 if (true == compilerResults.Errors.HasErrors)
41 {
42 StringBuilder sb = new System.Text.StringBuilder();
43 foreach (CompilerError ce in compilerResults.Errors)
44 {
45 sb.Append(ce.ToString());
46 sb.Append(System.Environment.NewLine);
47 }
48 throw new Exception(sb.ToString());
49 }
50
51 //生成代理实例,并调用方法
52 Assembly assembly = compilerResults.CompiledAssembly;
53 Type type = assembly.GetType(@namespace + "." + classname, true, true);
54 object obj = Activator.CreateInstance(type);
55 MethodInfo methodInfo = type.GetMethod(methodName);
56
57 return methodInfo.Invoke(obj, args);
58 }
59 catch (Exception ex)
60 {
61 throw ex;
62 }
63
64 string url = @"http://localhost:6568/Services/Test.asmx";
65
66 object obj = Tools.InvokeWebService(url, "TestMethod", new object[] { });
67 Response.Write(obj.ToString() + "</br></br>");
68
69 args = "{\"APPID\":1,\"APPName\":\"愤怒的小鸟\",\"APPVersion\":\"1.0\",\"ChannelNumber\":99886,\"PackageName\":\"123.123.123\"}";
70 obj = Tools.InvokeWebService(url, "AddAPPInfo", new object[] { args });
71 Response.Write(obj.ToString() + "</br></br>");
72
73