Error calling REST service

Asked

Viewed 331 times

-1

Yesterday good, my service worked, except for fields float, but commenting on this part until I have a solution, I was testing and running, in reality an Android APP to consume this service. Today I went to put on the air and gave me this problem. I tried to host on my site and gave too. This is the exploded error in the browser:

Error occurred. The type 'Objectcontent1' não pôde serializar o corpo da resposta para o tipo de conteúdo 'application/xml; charset=utf-8'. </ExceptionMessage> <ExceptionType>System.InvalidOperationException</ExceptionType> <StackTrace/> <InnerException> <Message>Ocorreu um erro.</Message> <ExceptionMessage> O tipo '<>f__AnonymousType47[System.String,System.String,System.String,System.String,System.String,System.String,System.Single]' cannot be serialized. Consider marking it with the attribute Datacontractattribute and mark all members you want to serialize with the attribute Datamemberattribute. If the type is a collection, consider marking it with Collectiondatacontractattribute. See Microsoft . NET Framework documentation for other types supported. System.Runtime.Serialization.Invaliddatacontractexception in System.Runtime.Serialization.DataContract.Datacontractcriticalhelper.Throwinvaliddatacontractexception(String message, Type type type) in System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, Runtimetypehandle typeHandle, Type type) in System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, Runtimetypehandle typeHandle, Type type) in System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContract(RuntimeTypeHandle typeHandle, Type type type) in System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlwriter, Object obj, Runtimetypehandle objectTypeHandle, Type objectType, Int32 declaredTypeID, Runtimetypehandle declaredTypeHandle, Type declaredType) in System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlwriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, Runtimetypehandle declaredTypeHandle) in Writearrayofanytypetoxml(Xmlwriterdelegator , Object , Xmlobjectserializerwritecontext , Collectiondatacontract ) in System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlwriter, Object obj, Xmlobjectserializerwritecontext context) in System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, Xmlwriterdelegator xmlwriter, Object obj, Runtimetypehandle declaredTypeHandle) in System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, Xmlwriterdelegator xmlwriter, Object obj, Boolean verifyKnownType, Runtimetypehandle declaredTypeHandle, Type declaredType) in System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, Xmlwriterdelegator xmlwriter, Object obj, Runtimetypehandle originalDeclaredTypeHandle, Type graphType) in System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator Writer, Object Graph, Datacontractresolver dataContractResolver) in System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator Writer, Object Graph, Datacontractresolver dataContractResolver) in System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator Writer, Object Graph, Datacontractresolver dataContractResolver) in System.Runtime.Serialization.DataContractSerializer.Writeobject(Xmlwriter Writer, Object Graph) in System.Net.Http.Formatting.Xmlmediatypeformatter.Writetostream(Type type type, Object value, Stream writeStream, Httpcontent content) in System.Net.Http.Formatting.Xmlmediatypeformatter.Writetostreamasync(Type type type, Object value, Stream writeStream, Httpcontent content, Transportcontext transportContext, Cancellationtoken cancellationToken) --- End of previous site stack tracking where the exception was generated --- in System.Runtime.Compilerservices.TaskAwaiter.Throwfornonsuccess(Task task) in System.Runtime.Compilerservices.TaskAwaiter.Handlenonsuccessanddebuggernotification(Task task) in System.Web.Http.WebHost.Httpcontrollerhandler.d__1b.Movenext()

Down with my service:

public class Autoriza
    {
        InetContext contexto = new InetContext();
        Liberacao liberacao = new Liberacao();
        public IEnumerable<object> getAutoriza()
        {
            var lista = contexto.Liberacoes
                .Join(contexto.ItensLibs, lib => lib.IdOrcamento, itens => itens.IdOrcamento, (lib, itens) => new { lib, itens })
                .Where(a => a.lib.IdOrcamento == a.itens.IdOrcamento)
                .Select(libera => new
                {
                    libera.lib.TipoVenda,
                    //libera.lib.Vencimento,
                    //libera.lib.Juros,
                    //libera.lib.Entrada,
                    //libera.lib.Acrescimo,
                    //libera.lib.Desconto,
                    libera.lib.Mensagem,
                    //libera.lib.DataLib,
                    libera.lib.Vendedor,
                    libera.lib.Cliente,
                    libera.lib.Filial,
                    libera.itens.Produto,
                    //libera.itens.Qtde,
                    //libera.itens.Unitario,
                    //libera.itens.Custo,
                    //libera.itens.CustoDiario,
                    libera.itens.UltCondicao
                    //libera.itens.Total
                }).ToList();

            return lista;
        }

My controller:

public class AutorizaController : ApiController
    {
        Autoriza autoriza = new Autoriza();

        [AcceptVerbs("Get")]
        public IEnumerable<object> getLiberacao()
        {
            return autoriza.getAutoriza().ToList();
        }
    }

I don’t know what might be going on. On my website is giving this error:

User login failure 'REDEHOST meudomínio.co_web'

My attempts: See that the error suggests putting some attributes in the class and I did it and even then, it didn’t work. What I don’t understand is that yesterday, without me touching anything, it worked except for the float.

This error is also on the site and found me, but because Sql Server was out:

The underlying Provider failed on Open.

I talked to the provider (REDEHOST) about it, but I got no answer, as always from redehost.

EDIT1 My class of entity:

[Table("LIBERACAO")]
    public class Liberacao
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("ID_LIBERACAO")]
        public int IdLiberacao { get; set; }
        [Column("FLAG_LIBERACAO")]
        public byte FlagLiberacao { get; set; }
        [Column("ID_ORCAMENTO")]
        public int IdOrcamento { get; set; }
        [Column("ID_VENDEDOR")]
        public int IdVendedor { get; set; }
        [Column("VENDEDOR")]
        public string Vendedor { get; set; }
        [Column("ID_FILIAL")]
        public int IdFilial { get; set; }
        [Column("FILIAL")]
        public string Filial { get; set; }
        [Column("DATALIB")]
        public float DataLib { get; set; }
        [Column("HORALIB")]
        public float HoraLib { get; set; }
        [Column("ID_CLIENTE")]
        public int IdCliente { get; set; }
        [Column("CLIENTE")]
        public string Cliente { get; set; }
        [Column("TIPO_VENDA")]
        public string TipoVenda { get; set; }
        [Column("JUROS")]
        public float Juros { get; set; }
        [Column("DESCONTO")]
        public float Desconto { get; set; }
        [Column("VENCIMENTO")]
        public float Vencimento { get; set; }
        [Column("ACRESCIMO")]
        public float Acrescimo { get; set; }
        [Column("ENTRADA")]
        public float Entrada { get; set; }
        [Column("PRAZO")]
        public float Prazo { get; set; }
        [Column("TOTAL_LIQUIDO")]
        public float TotalLiquido { get; set; }
        [Column("MIN_TOTAL")]
        public float MinTotal { get; set; }
        [Column("USUARIO")]
        public string Usuario { get; set; }
        [Column("CUSTODIARIO")]
        public Decimal CustoDiario { get; set; }
        [Column("MAX_COMI")]
        public Decimal MaxComi { get; set; }
        [Column("VALOR_COMI")]
        public Decimal ValorComi { get; set; }
        [Column("NOVA_COMI")]
        public Decimal NovaComi { get; set; }
        [Column("MENSSAGEM")]
        public string Mensagem { get; set; }
        [Column("Menssagem_RET")]
        public string MensagemRet { get; set; }
        [Column("DataRetorno")]
        public double DataRetorno { get; set; }
        [Column("HoraRetorno")]
        public double HoraRetorno { get; set; }
        [Column("TempoProcesso")]
        public double TempoPrecesso { get; set; }
        [Column("Tipo")]
        public int Tipo { get; set; }
        [Column("PROGRAMA")]
        public string Programa { get; set; }
        [Column("NOME_PC")]
        public string NomePc { get; set; }
        [Column("NOME_PROCEDURE")]
        public string NomeProcedure { get; set; }
        [Column("Perc_Juros_Total")]
        public decimal PercJurosTotal { get; set; }
        [Column("FLAG_CULTURAVENCIDA")]
        public byte FlagCulturaVencida { get; set; }
        [Column("CULTURA")]
        public string Cultura { get; set; }
        [Column("CULTURA_VCTO")]
        public int CulturaVcto { get; set; }
        [Column("FLAG_PRORROGADO")]
        public byte FlagProrrogado { get; set; }
        [Column("VALOR_PRORROGADO")]
        public double ValorProrrogado { get; set; }
        [Column("DIAS_ATRASO")]
        public int DiasAtrazo { get; set; }
        [Column("ID_VENDEDOR2")]
        public int IdVendedor2 { get; set; }
        [Column("VENDEDOR2")]
        public string Vendedor2 { get; set; }
        [Column("COMISSAO_VEND2")]
        public double ComissaoVend2 { get; set; }
        [Column("FLAG_COTACAO")]
        public byte FlagCotacao { get; set; }
        [Column("TipoVenda")]
        public string TipoVenda1 { get; set; }
        [Column("Flag_Receber_Atrasado")]
        public byte FlagReceberAtrazado { get; set; }
        [Column("Autorizou_Receber_Atrasado")]
        public string AutorizouReceberAtrazado { get; set; }

    }

[Table("ITENSLIB")]
    public class ItensLib
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("ID_ITENSLIB")]
        public int IdItensLib { get; set; }
        [Column("ID_ORCAMENTO")]
        public int IdOrcamento { get; set; }
        [Column("ID_PRODUTO")]        
        public int IdProduto { get; set; }
        [Column("PRODUTO")]
        public string Produto { get; set; }
        [Column("QTDE")]
        public float Qtde { get; set; }
        [Column("UNITARIO")]
        public float Unitario { get; set; }
        [Column("CUSTO")]
        public float Custo { get; set; }
        [Column("MINIMO")]
        public float Minimo { get; set; }
        [Column("TOTAL")]
        public float Total { get; set; }
        [Column("CUSTODIARIO")]
        public Double CustoDiario { get; set; }
        [Column("FABRICANTE")]
        public string Fabricante { get; set; }
        [Column("ULT_CONDICAO")]
        public Double UltCondicao { get; set; }
        [Column("PROGRAMA")]
        public string Programa { get; set; }
        [Column("NOME_PC")]
        public string NomePc { get; set; }
        [Column("NOME_PROCEDURE")]
        public string NomeProcedure { get; set; }
        [Column("Flag_Vencido")]
        public byte FlagVencido { get; set; }
        [Column("TipoVenda")]
        public string TipoVenda { get; set; }
        [Column("VENDA_VISTA")]
        public float VendaVista { get; set; }
        [Column("MARGEM_AVISTA")]
        public float MargemAvista { get; set; }
        [Column("QTDE_NEG_AVISTA")]
        public float QtdNegAvista { get; set; }
        [Column("VENDA_PRAZO")]
        public float VendaPrazo { get; set; }
        [Column("PM_PRAZO")]
        public float PmPrazo { get; set; }
        [Column("MARGEM_PRAZO")]
        public float MargemPrazo { get; set; }
        [Column("JUROS_PRAZO")]
        public float JurosPrazo { get; set; }
        [Column("QTDE_PRAZO")]
        public float QtdePrazo { get; set; }
        [Column("VENDA_VISTA_ANT")]
        public float VendaVistaAnt { get; set; }
        [Column("MARGEM_AVISTA_ANT")]
        public float MargemAvistaAnt { get; set; }
        [Column("QTDE_NEG_AVISTA_ANT")]
        public float QtdeNegAvistaAnt { get; set; }
        [Column("VENDA_PRAZO_ANT")]
        public float VendaPrazoAnt { get; set; }
        [Column("PM_PRAZO_ANT")]
        public float PmPrazoAnt { get; set; }
        [Column("MARGEM_PRAZO_ANT")]
        public float MargemPrazoAnt { get; set; }
        [Column("JUROS_PRAZO_ANT")]
        public float JurosPrazoAnt { get; set; }
        [Column("QTDE_PRAZO_ANT")]
        public float QtdePrazoAnt { get; set; }
        [Column("VENDA_VISTA_ANT1")]
        public float VendaVistaAnt1 { get; set; }
        [Column("MARGEM_AVISTA_ANT1")]
        public float MargemAvistaAnt1 { get; set; }
        [Column("QTDE_NEG_AVISTA_ANT1")]
        public float QtdeNegAvistaAnt1 { get; set; }
        [Column("VENDA_PRAZO_ANT1")]
        public float VendaPrazoAnt1 { get; set; }
        [Column("PM_PRAZO_ANT1")]
        public float PmPrazoAnt1 { get; set; }
        [Column("MARGEM_PRAZO_ANT1")]
        public float MargemPrazoAnt1 { get; set; }
        [Column("JUROS_PRAZO_ANT1")]
        public float JurosPrazoAnt1 { get; set; }
        [Column("QTDE_PRAZO_ANT1")]
        public float QtdePrazoAnt1 { get; set; }
    }
  • Can you consume the service of another application? For example using Postman? Checked if there is no authentication problem for the user co_web, for example, expired password?

  • @Ricardopunctual, yesterday I was testing by Postman and was ok, no problem. Today I could not. I tried a service that I took a tutorial of Macoretti and it didn’t work either, but maybe the service was out, I thought. What we don’t understand is co_web. I don’t know what this is.

  • I thought about it because of the mistake you mentioned "User login failure 'REDEHOST meudomínio.co_web'"

  • @Ricardopunctual, I think my service is bugged and by Gabriel’s response, it may have to do, because I climbed another service that I did to my site and is ok, including being consumed by my Android App that I’m doing, so I think it’s really the service. Plus, I thank you all.

1 answer

1

It is not interesting to work with entities (or object in your case) from the database directly in your Controller because your data may come in a formatting that your serializer may not understand or format wrong. My recommendation to avoid these float formatting errors you are experiencing is to use a model class with mapping and formatting your data to facilitate this serialization.

For example, I could use Automapper to do this formatting:

CreateMap<Liberacao, LiberacaoModel>()
                .ForMember(d => d.Juros, m => m.MapFrom(s => s.Juros.ToString("C3")));

In my example, now I am ensuring that my Interest will always have three decimal places and properly formatted so as not to break my serialization.

What I understood of your code and error, your serializer does not understand this . Join() ai when you return them as a object, It’s hard to know without the two entities that you make the Join to analyze.

  • 1

    Okay, I think Gabriel Coletta is right. I did another job and it worked properly. I think you killed, probably another situation. I’m posting the two entities (my domain classes), as you commented.

  • I noticed that you are using the Double class instead of the double type, and according to a fraction of the stack error: [System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Single]' cannot be serialized. He’s not getting to serialize him.

  • I did this just for testing, because with float or double was giving error and I only got with one attribute work, but the others also continued with the error

  • I’m redoing the whole project, because it was right at the beginning and I got it, now I need to create the service that will deliver and the method in the model that I was using, passing an object, I will have to redo, following your comment, but I never used the Automapper. I need to read something from him

  • There are several similar options, even the possibility of doing a method that does this mapping yourself. I recommended the Automapper because it is the one with the most experience.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.