Inquiridor
Não foi possível criar um canal seguro para SSL/TLS, erro ocorre na segunda vez que chamo o webservice

Pergunta
-
Estou tendo este problema na segunda vez que chamo o webservice.
Sempre na primeira vez funciona, porém na segunda não...
Alguem poderia me ajudar?
o erro ocorre nessa linha:
var teste = tipoInstance.GetMethod(methodName).Invoke(wsvcClass, args);
Segue o codigo:
ConnectionLib.WsProxy opa = new ConnectionLib.WsProxy(); opa.CallWebService("https://urldoservico" , "NfseServicesService" //nome do servico , "EnviarLoteRpsSincrono" //nome do metodo , new object[]{ File.ReadAllText(@"arquivo.xml") } , new X509Certificate2(@"C:\Projetos\Branch\Framework\NFE\Certificado\certificado.pfx", "senhadocertificado"));
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using System.Security.Permissions; using System.Web.Services.Description; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Net.Security; namespace ConnectionLib { class BressamWebClient : WebClient { public bool CertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErros) { return true; } X509Certificate Certificado; public BressamWebClient(X509Certificate Certificado) { this.Certificado = Certificado; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidation); } protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); (request as HttpWebRequest).ClientCertificates.Add(this.Certificado); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidation); return request; } } public class WsProxy { public bool CertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErros) { return true; } [SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] public object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args, X509Certificate certificado) { using (BressamWebClient client = new BressamWebClient(certificado)) { // Connect To the web service using (System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl")) { // Now read the WSDL file describing a service. ServiceDescription description = ServiceDescription.Read(stream); ///// LOAD THE DOM ///////// // Initialize a service description importer. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //importer.ProtocolName = "Soap"; // Use SOAP 1.2. importer.AddServiceDescription(description, string.Empty, string.Empty); // Generate a proxy client. importer.Style = ServiceDescriptionImportStyle.Client; // Generate properties to represent primitive values. importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; // Initialize a Code-DOM tree into which we will import the service. CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit1 = new CodeCompileUnit(); unit1.Namespaces.Add(nmspace); // Import the service into the Code-DOM tree. This creates proxy code that uses the service. ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1); if (warning == 0) // If zero then we are good to go { // Generate the proxy code using (CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp")) { // Compile the assembly proxy with the appropriate references string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" }; CompilerParameters parms = new CompilerParameters(assemblyReferences); parms.GenerateExecutable = false; parms.GenerateInMemory = true; parms.TreatWarningsAsErrors = false; parms.WarningLevel = 4; CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1); // Check For Errors if (results.Errors.Count > 0) { foreach (CompilerError oops in results.Errors) { System.Diagnostics.Debug.WriteLine("========Compiler error============"); System.Diagnostics.Debug.WriteLine(oops.ErrorText); } throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window."); } // Finally, Invoke the web service method object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName); Type tipoInstance = wsvcClass.GetType(); object oClientCertificates = tipoInstance.InvokeMember("ClientCertificates", System.Reflection.BindingFlags.GetProperty, null, wsvcClass, new Object[] { }); Type tipoClientCertificates = oClientCertificates.GetType(); tipoClientCertificates.InvokeMember("Add", System.Reflection.BindingFlags.InvokeMethod, null, oClientCertificates, new Object[] { certificado }); var teste = tipoInstance.GetMethod(methodName).Invoke(wsvcClass, args); stream.Close(); return teste; } } else { stream.Close(); return null; } } } } } }
System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada. ---> System.Net.WebException: A solicitação foi anulada: Não foi possível criar um canal seguro para SSL/TLS.
em System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
em System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
em System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
em NfseServicesService.EnviarLoteRpsSincrono(String xml)
--- Fim do rastreamento de pilha de exceções internas ---
em System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
em System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
em System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
em System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
em ConnectionLib.WsProxy.CallWebService(String webServiceAsmxUrl, String serviceName, String methodName, Object[] args, X509Certificate certificado) na c:\Users\RaphaelN.Bressam.bressampc\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\BressamProxy.cs:linha 110
- Editado Raphael N. Bressam sábado, 22 de março de 2014 22:21
Todas as Respostas
-
-
-
-
Raphael,
Tente adicionando esta linha: ServicePointManager.Expect100Continue= true;
Referência:
ServicePointManager.Expect100Continue Property
Att,
Antero Marques
____________________________________________________________________________
Se a resposta for útil, marque como útil, se respondeu totalmente sua dúvida, marque como resposta.
O Fórum MSDN é utilizado também como base de conhecimento, então é responsabilidade de todos mantê-lo organizado e funcional.
- Editado Antero Marques quinta-feira, 31 de março de 2016 18:25
-