Fórum SeFaz Consulta Cadastro #460280
06/11/2013
0
Estou com um problema gigante que é o consumo do web service de Consulta de Cadastro.
Estou fazendo em C#, desenvolvendo uma DLL para consulta para poder chamar em um sistema de terceiro.
Porém estou usando SOAP 1.2 e o bidding é o customBidding.
Quando executo ocorre o seguinte problema:
System.InvalidOperationException: O nome de usuário não foi fornecido. Especifique o nome de usuário em ClientCredentials.
Alguém já passou por isso?
Josivan Laskoski
Curtir tópico
+ 0Post mais votado
05/01/2016
Já tentou algo assim?
SEUWS.ClientCredentials.UserName.UserName = "SEU_USUARIO";
SEUWS.ClientCredentials.UserName.Password = "SUA_SENHA";
Isso tudo antes de invocar o método que executa a chamada direta do WS?
Josivan Laskoski
Gostei + 1
Mais Posts
18/11/2013
Fabio Nascimento..
Há um propriedade ClientCredentials onde vc o informa.
Gostei + 0
05/01/2016
Victor Boechat
Estou passando o mesmo problema e não encontro solução de jeito nenhum.
Gostei + 0
05/01/2016
Josivan Laskoski
Desculpe pela falta de respostas, acabei até esquecendo desse post, que ainda estava em um email antigo que não usava mais.
Basicamente fiz dessa forma que segue o codigo abaixo.
Adicionei a referencia do WS da SeFaz como uma Web References com o nome de CadConsultaWebEstados.
public class SeFazConsultaWebEstados
{
private CadConsultaWebEstados.CadConsultaCadastro2 cons = new CadConsultaWebEstados.CadConsultaCadastro2();
private CadConsultaWebEstados.nfeCabecMsg cab = new CadConsultaWebEstados.nfeCabecMsg();
[WebMethod]
public String ConsultaCadastro(string _uf, string _versaoDados, string _ufConsulta, string _ieContribuinte, string _cnpj, string _cpf, string _caminhoCertificadoDigital, string _senhaCertificadoDigital, string _Url)
{
/********************* Certificado **********************************/
X509Certificate2 certificado = new X509Certificate2(_caminhoCertificadoDigital, _senhaCertificadoDigital, X509KeyStorageFlags.PersistKeySet);
/********************* Certificado **********************************/
/********************* Estrutura XML Envio **********************************/
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", String.Empty));
XmlNode nodeCab = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "ConsCad", "");
XmlAttribute atributoVersao = xmlDoc.CreateAttribute("versao");
atributoVersao.Value = _versaoDados;
nodeCab.Attributes.Append(atributoVersao);
XmlAttribute atributoxml = xmlDoc.CreateAttribute("xmlns");
atributoxml.Value = "http://www.portalfiscal.inf.br/nfe";
nodeCab.Attributes.Append(atributoxml);
xmlDoc.AppendChild(nodeCab);
XmlNode nodeInf = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "infCons", "");
nodeCab.AppendChild(nodeInf);
XmlNode userNode = xmlDoc.CreateElement("xServ");
userNode.InnerText = "CONS-CAD";
nodeInf.AppendChild(userNode);
userNode = xmlDoc.CreateElement("UF");
userNode.InnerText = _ufConsulta;
nodeInf.AppendChild(userNode);
if (!_ieContribuinte.Equals(""))
{
userNode = xmlDoc.CreateElement("IE");
userNode.InnerText = _ieContribuinte;
nodeInf.AppendChild(userNode);
}
if (!_cnpj.Equals(""))
{
userNode = xmlDoc.CreateElement("CNPJ");
userNode.InnerText = _cnpj;
nodeInf.AppendChild(userNode);
}
if (!_cpf.Equals(""))
{
userNode = xmlDoc.CreateElement("CPF");
userNode.InnerText = _cpf;
nodeInf.AppendChild(userNode);
}
/********************* Estrutura XML Envio **********************************/
/********************* Configuracao **********************************/
cons.Timeout = 70000;
cons.nfeCabecMsgValue = cab;
cons.nfeCabecMsgValue.cUF = _uf;
cons.nfeCabecMsgValue.versaoDados = _versaoDados;
cons.Url = _Url;
cons.ClientCertificates.Add(certificado);
/********************* Transforma XML em String **********************************/
XmlDocument xmld = new XmlDocument();
xmld.LoadXml(xmlDoc.InnerXml.ToString());
/********************* Transforma XML em String **********************************/
/********************* Envio e Retorno **********************************/
XmlNode status = cons.consultaCadastro2(xmld);
String sTexto = status.InnerXml;
sTexto = sTexto.Substring(52, sTexto.Length - 52);
sTexto = "<infCons >" + sTexto;
XmlTextReader reader = new XmlTextReader(new StringReader(sTexto));
ArrayList elementos = new ArrayList();
String sNome = "";
while ((reader.Read()))
{
if (!reader.Name.Equals("")){
sNome = reader.Name;
}
switch (reader.NodeType)
{
case XmlNodeType.Element:
//Se existirem atributos
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
//Pega o valor do atributo.
elementos.Add(sNome + "|");
elementos.Add(reader.Value + "|");
}
}
break;
case XmlNodeType.Text:
//Incluir o texto do elemento no ArrayList
elementos.Add(sNome + "|");
elementos.Add(reader.Value + "|");
break;
}
}
String retorno = "";
foreach (var num in elementos)
{
retorno = retorno + num;
}
return retorno;
}
Espero que ajude!
Gostei + 0
05/01/2016
Victor Boechat
Gostei + 0
05/01/2016
Josivan Laskoski
Chamada da configuração:
var configuracao = Funcao.ConfiguracaoWebConfig(
"link");
var enviaClient = new SI_ProcessaConsultaNFSync_OBClient(configuracao.binding,
configuracao.endPoint);
enviaClient.ClientCredentials.UserName.UserName = usuario;
enviaClient.ClientCredentials.UserName.Password = senha;
Função da Configuração
public static ConfiguracaoWS ConfiguracaoWebConfig(string link_endPoint)
{
try
{
var endPoint = new EndpointAddress(new Uri(link_endPoint));
var basicHttpBinding = new BasicHttpBinding
{
Name = "RequestSoap",
Security =
{
Mode = BasicHttpSecurityMode.TransportCredentialOnly,
Transport =
{
ClientCredentialType = HttpClientCredentialType.Basic,
ProxyCredentialType = HttpProxyCredentialType.Basic
},
Message =
{
ClientCredentialType = BasicHttpMessageCredentialType.UserName
}
},
ReaderQuotas =
{
MaxStringContentLength = 2147483647,
MaxArrayLength = 2147483647,
MaxBytesPerRead = 2147483647,
MaxDepth = 2147483647,
MaxNameTableCharCount = 2147483647,
},
MaxBufferPoolSize = 52428800,
MaxBufferSize = 65536000,
MaxReceivedMessageSize = 65536000
};
return new ConfiguracaoWS
{
endPoint = endPoint,
binding = basicHttpBinding
};
}
catch (Exception ex)
{
return null;
}
public class ConfiguracaoWS
{
public EndpointAddress endPoint { get; set; }
public BasicHttpBinding binding { get; set; }
}
Gostei + 1
06/01/2016
Victor Boechat
Consegui informar o usuário e senha do WebService, no entanto retorna o seguinte erro:
Informações adicionais: A operação unidirecional retornou uma mensagem não nula com Ação=''.
Pensei que o problema fosse que eu estivesse informando algum atributo null ou em branco no objeto que estou enviando, no entanto não é isso. Alguém tem ideia do que seja?
Gostei + 0
06/01/2016
Josivan Laskoski
Victor, você tem o stack trace desse erro? Já tentou usar o SoapUI para fazer testes de conexão?
Gostei + 0
06/01/2016
Victor Boechat
Segue o StackTrace:
System.ServiceModel.ProtocolException não foi manipulada
HResult=-2146233087
Message=A operação unidirecional retornou uma mensagem não nula com Ação=''.
Source=mscorlib
StackTrace:
Server stack trace:
em System.ServiceModel.Dispatcher.RequestChannelBinder.ValidateNullReply(Message message)
em System.ServiceModel.Dispatcher.RequestChannelBinder.Send(Message message, TimeSpan timeout)
em System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
em System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
em System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
em System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
em System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
em BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_Out.OP_ReceberVendSupSet(OP_ReceberVendSupSet request)
em BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_OutClient.BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_Out.OP_ReceberVendSupSet(OP_ReceberVendSupSet request) na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Service References\Setores_Vendedores_Supervisores\Reference.cs:linha 386
em BoechatSoft.Integrador.Setores_Vendedores_Supervisores.SI_EstrutVenda_OutClient.OP_ReceberVendSupSet(DT_SetVendSup MT_SetVendSup) na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Service References\Setores_Vendedores_Supervisores\Reference.cs:linha 392
em BoechatSoft.Integrador.Integracao.VendSupSet() na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Integracao.cs:linha 111
em BoechatSoft.Integrador.Integracao.Integrar() na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Integracao.cs:linha 32
em BoechatSoft.Integrador.IntegracaoFrm.button1_Click(Object sender, EventArgs e) na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\IntegracaoFrm.cs:linha 28
em System.Windows.Forms.Control.OnClick(EventArgs e)
em System.Windows.Forms.Button.OnClick(EventArgs e)
em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
em System.Windows.Forms.Control.WndProc(Message& m)
em System.Windows.Forms.ButtonBase.WndProc(Message& m)
em System.Windows.Forms.Button.WndProc(Message& m)
em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
em System.Windows.Forms.Application.Run(Form mainForm)
em BoechatSoft.Integrador.Program.Main() na C:\Users\Victor\Documents\Visual Studio 2015\Projects\BoechatSoft_Integrador\BoechatSoft.Integrador\Program.cs:linha 19
em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
em System.Threading.ThreadHelper.ThreadStart()
InnerException:
Gostei + 0
06/01/2016
Josivan Laskoski
Como voce está configurando o WS?
Gostei + 0
07/01/2016
Victor Boechat
Gostaria de agradecer pela ajuda!
Para resolver basta alterar a propriedade IsOneWay para false, no meu caso, essa propriedade ficava na assinatura dos métodos da interface de mapeamento com classe do WebService.
Gostei + 0
08/01/2016
Josivan Laskoski
Se possível vote nas respostas que te ajudaram e se puder, coloque aqui a parte do fonte que você resolveu isso.
Abraços
Gostei + 0
08/01/2016
Victor Boechat
Segue o código
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://xxxxxxxxxxx.com.br/INTEGRA_REVENDAS/receberPDV", ConfigurationName="PDV.SI_PDV_Out")]
public interface SI_PDV_Out {
// CODEGEN: Gerando contrato de mensagem porque a operação OP_ReceberPDV não é RPC nem documento codificado.
[System.ServiceModel.OperationContractAttribute(IsOneWay=false, Action="http://xxx.com/xi/WebService/soap1.1")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
void OP_ReceberPDV(BoechatSoft.Integrador.PDV.OP_ReceberPDV request);
[System.ServiceModel.OperationContractAttribute(IsOneWay=false, Action="http://xxx.com/xi/WebService/soap1.1")]
System.Threading.Tasks.Task OP_ReceberPDVAsync(BoechatSoft.Integrador.PDV.OP_ReceberPDV request);
}Alterei o IsOneWay de true para false
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)