C#动态调用webService出现 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系。


在远程调用WebService时出现下面的情况:

              

这种情况一般是由于证书有问题时出现,如果在浏览器中打开是这种情况:

           

 

解决方法新建一个类,代码如下:

 1     public static class CertificateTrust
 2     {
 3  
 4         public static void SetCertificatePolicy()
 5         {
 6             ServicePointManager.ServerCertificateValidationCallback
 7                        += RemoteCertificateValidate;
 8         }  
 9         private static bool RemoteCertificateValidate(
10            object sender, X509Certificate cert,
11             X509Chain chain, SslPolicyErrors error)
12         {
13             
14             System.Console.WriteLine("Warning, trust any certificate");
15             return true;
16         }
17     } 

 

在动态编译WebService的代码中调用上面的类就可以了,注意调用的位置,一定要在打开前调用,下面代码的红色部分

动态编译WebSerivce的代码如下:

 1     public class WSHelper
 2     {
 3         /// < summary>           
 4         /// 动态调用web服务         
 5         /// < /summary>          
 6         /// < param name="url">WSDL服务地址< /param> 
 7         /// < param name="methodname">方法名< /param>           
 8         /// < param name="args">参数< /param>           
 9         /// < returns>< /returns>          
10         public static object InvokeWebService(string url, string methodname, object[] args)
11         {
12             return WSHelper.InvokeWebService(url, null, methodname, args);
13         }
14         /// < summary>          
15         /// 动态调用web服务 
16         /// < /summary>          
17         /// < param name="url">WSDL服务地址< /param>
18         /// < param name="classname">类名< /param>  
19         /// < param name="methodname">方法名< /param>  
20         /// < param name="args">参数< /param> 
21         /// < returns>< /returns>
22         public static object InvokeWebService(string url, string classname, string methodname, object[] args)
23         {
24             string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
25             if ((classname == null) || (classname == ""))
26             {
27                 classname = WSHelper.GetWsClassName(url);
28             }
29             try
30             {   //获取WSDL   
31                 WebClient wc = new WebClient();
32 
33                 CertificateTrust.SetCertificatePolicy();//证书出现问题时调用此代码
34 
35                 Stream stream = wc.OpenRead(url + "?WSDL");
36                 ServiceDescription sd = ServiceDescription.Read(stream);
37                 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
38                 sdi.AddServiceDescription(sd, "", "");
39                 CodeNamespace cn = new CodeNamespace(@namespace);
40                 //生成客户端代理类代码          
41                 CodeCompileUnit ccu = new CodeCompileUnit();
42                 ccu.Namespaces.Add(cn);
43                 sdi.Import(cn, ccu);
44                 CSharpCodeProvider icc = new CSharpCodeProvider();
45                 //设定编译参数添加所需要的DLL文件                 
46                 CompilerParameters cplist = new CompilerParameters();
47                 cplist.GenerateExecutable = false;
48                 cplist.GenerateInMemory = true;
49                 cplist.ReferencedAssemblies.Add("System.dll");
50                 cplist.ReferencedAssemblies.Add("System.XML.dll");
51                 cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
52                 cplist.ReferencedAssemblies.Add("System.Data.dll");
53                 //编译代理类                 
54                 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
55                 if (true == cr.Errors.HasErrors)
56                 {
57                     System.Text.StringBuilder sb = new System.Text.StringBuilder();
58                     foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
59                     {
60                         sb.Append(ce.ToString());
61                         sb.Append(System.Environment.NewLine);
62                     }
63                     throw new Exception(sb.ToString());
64                 }
65                 //生成代理实例,并调用方法   
66                 System.Reflection.Assembly assembly = cr.CompiledAssembly;
67                 Type t = assembly.GetType(@namespace + "." + classname, true, true);
68                 object obj = Activator.CreateInstance(t);
69                 System.Reflection.MethodInfo mi = t.GetMethod(methodname);
70                 return mi.Invoke(obj, args); 
71             }
72             catch (Exception ex)
73             {
74                 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
75             }
76         }
77         private static string GetWsClassName(string wsUrl)
78         {
79             string[] parts = wsUrl.Split('/');
80             string[] pps = parts[parts.Length - 1].Split('.');
81             return pps[0];
82         }
83     }

 

调用动态编译的代码如下:

1                 string url = "http://localhost:81/WebServiceLogin.asmx";
2                 string[] args = new string[2];
3                 args[0] = "参数1";
4                 args[1] = "参数2";
5                 object result = WSHelper.InvokeWebService(url, "HelloWorld", args);
View Code

 

智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告