none
Consumo webservice receita parana RRS feed

  • Pergunta

  • Estou tentando consumir um webservice da receita estadual do Paraná criando dinamicamente o webrequest/webresponse. Porem o resultado da requisição retorno none.

    o webservice é:https://nfe.sefa.pr.gov.br/nfe/CadConsultaCadastro4?wsdl

    A classe que estou usando para acessar o webservice é a seguinte:

    public class WebServiceInvoker
        {
            List<string> _availableServices;
            Dictionary<string, Type> _availableTypes;
            Assembly _webServiceAssembly;
            X509Certificate2 _oCertificado;

            public WebServiceInvoker(Uri webServiceUri)
            {
                _availableServices = new List<string>();
                _availableTypes = new Dictionary<string, Type>();

                _webServiceAssembly = BuildAssemblyFromWSDL(webServiceUri);
                            
                Type[] types = _webServiceAssembly.GetExportedTypes();

                foreach (Type type in types)
                {
                    _availableServices.Add(type.FullName);
                    _availableTypes.Add(type.FullName, type);
                }
            }

            public List<string> AvailableServices
            {
                get { return _availableServices; }
            }
            public Dictionary<string, Type> AvailableTypes
            {
                get { return _availableTypes; }
            }

            private ServiceDescriptionImporter BuildServiceDescriptionImporter(XmlTextReader xmlReader)
            {
                if (!ServiceDescription.CanRead(xmlReader))
                    throw new Exception("WebService Description é inválido.");

                ServiceDescription serviceDescription = ServiceDescription.Read(xmlReader);

                ServiceDescriptionImporter descriptionImporter = new ServiceDescriptionImporter();
                descriptionImporter.AddServiceDescription(serviceDescription, null, null);
                descriptionImporter.Style = ServiceDescriptionImportStyle.Client;
                descriptionImporter.CodeGenerationOptions =
                    System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

                return descriptionImporter;
            }

            private Assembly CompileAssembly(ServiceDescriptionImporter descriptionImporter)
            {
                CodeNamespace codeNamespace = new CodeNamespace();
                CodeCompileUnit codeUnit = new CodeCompileUnit();

                codeUnit.Namespaces.Add(codeNamespace);

                ServiceDescriptionImportWarnings importWarnings =
                    descriptionImporter.Import(codeNamespace, codeUnit);

                if (importWarnings == 0)
                {
                    CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
                    string[] refereces = new string[2] {"System.Web.Services.dll", "System.Xml.dll"};
                    CompilerParameters parameters = new CompilerParameters(refereces);
                    CompilerResults results = compiler.CompileAssemblyFromDom(parameters, codeUnit);

                    foreach(CompilerError oops in results.Errors)
                    {
                        throw new Exception("Erro ao compilar o webservice: " + oops.ErrorText);
                    }

                    return results.CompiledAssembly;
                }
                else
                {
                    throw new Exception("O WSDL é inválido.");
                }
            }

            private Assembly BuildAssemblyFromWSDL(Uri webServiceUri)
            {
                if (string.IsNullOrEmpty(webServiceUri.ToString()))
                    throw new Exception("A Uri do webservice não foi informada.");

                X509Certificate2 oX509Cert = new X509Certificate2();
                X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 =
                    (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2Collection collection2 =
                    (X509Certificate2Collection)collection1.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);
                X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(
                    collection2, "Certificado(s) digita(is) disponível(is)", "Selecione o certificado digital para uso",
                    X509SelectionFlag.SingleSelection);
                if (scollection.Count == 0)
                    throw new Exception("O cetificado selecionado não é válido ou nenhum certificado foi selecionado.");
                else
                    _oCertificado = scollection[0];

                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback = (s, c, n, p) => { return true; };

                HttpWebRequest wr =
                    (HttpWebRequest)HttpWebRequest.Create(webServiceUri.OriginalString + "?wsdl");
                //wr.Method = "POST";
                //wr.ContentType = "application/json";
                //wr.ContentType = "application/x-www-form-urlencoded";
                //wr.ContentType = "text/xml";

                wr.ClientCertificates.Add(_oCertificado);
           
                HttpWebResponse wres = (HttpWebResponse)wr.GetResponse();

                long teste = wres.ContentLength;

                StreamReader readerWres = new StreamReader(wres.GetResponseStream());
                //string teste = readerWres.ReadToEnd();
                
                XmlTextReader xmlReader = new XmlTextReader(wres.GetResponseStream());
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServiceDescriptionImporter descriptionImporter = BuildServiceDescriptionImporter(xmlReader);

                return CompileAssembly(descriptionImporter);
            }

            public T InvokeMethod<T> (string serviceName, string methodName, params object[] args)
            {
                object obj = _webServiceAssembly.CreateInstance(serviceName);
                Type type = obj.GetType();

                object clientCertificates = type.InvokeMember("ClientCertificates",
                    System.Reflection.BindingFlags.GetProperty, null, obj, new Object[] { });
                Type tipoClientCertificates = clientCertificates.GetType();
                tipoClientCertificates.InvokeMember("Add",
                    System.Reflection.BindingFlags.InvokeMethod, null, clientCertificates, new Object[] { _oCertificado });
                
                return (T)type.InvokeMember(methodName, BindingFlags.InvokeMethod, null, obj, args);
            }

            public List<string> EnumerateServiceMethods(string serviceName)
            {
                List<string> methods = new List<string>();

                if (!_availableTypes.ContainsKey(serviceName))
                    throw new Exception("Service Not Available");
                else
                {
                    Type type = _availableTypes[serviceName];

                    foreach (MethodInfo minfo in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
                        methods.Add(minfo.Name);

                    return methods;
                }
            }
        }

    Alguem já passou por esse problema?


    segunda-feira, 16 de novembro de 2020 03:29

Todas as Respostas