-2

minha questão é a seguinte: criei um endpoint em uma aplicação C# para registrar uma nova entrada no sistema a partir de dados contidos em um arquivo XML de uma nota fiscal, estou usando a biblioteca Zeus.Net.NFe.NFCe versão 1.0.1.1149, segue o código

private readonly string _caminhoXml;
    private readonly IEntradaAppService _entradaAppService;
    public EntradaController(IMediatorHandler handler,
                                INotificationHandler<DomainNotification> notification,
                                IEntradaAppService entradaAppService) : base(handler, notification)
    {
        _entradaAppService = entradaAppService;
        _caminhoXml = @"";
    }

    [Route("xml")]
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status201Created)]
    public async Task<IActionResult> PostPorXml(IFormFileCollection file, string homeCareId)
    {
        try
        {
            IFormFileCollection arquivo = Request.Form.Files;
            if (arquivo.Count > 0 || arquivo != null)
            {
                try
                {
                    foreach (var arq in arquivo)
                    {
                        using var fileStream = new FileStream(_caminhoXml + arq.FileName, FileMode.Create);
                        await arq.CopyToAsync(fileStream);

                        var xml = new nfeProc().CarregarDeArquivoXml(_caminhoXml + arq.FileName); // <- quebra aqui

                        var produtos = new List<ItemEntradaDto>();
                        Parallel.ForEach(xml.NFe.infNFe.det, produto =>
                        {
                            produtos.Add(new ItemEntradaDto
                            {
                                CodigoProdutoFornecedor = produto.prod.cProd,
                                CodigoEan = produto.prod.cEAN,
                                NomeProduto = produto.prod.xProd,
                                Quantidade = produto.prod.qCom,
                                ValorUnitario = produto.prod.vUnCom,
                                ValorTotal = produto.prod.vProd
                            });
                        });

                        var entrada = new EntradaPorNfInputModel();
                        entrada.HomeCareId = homeCareId;
                        entrada.ChaveNf = xml.protNFe.infProt.chNFe;
                        entrada.CnpjFornecedor = xml.NFe.infNFe.emit.CNPJ;
                        entrada.RazaoSocialFornecedor = xml.NFe.infNFe.emit.xNome;
                        entrada.NomeFantasiaFornecedor = xml.NFe.infNFe.emit.xFant;
                        entrada.LogradouroFornecedor = xml.NFe.infNFe.emit.enderEmit.xLgr;
                        entrada.NumeroFornecedor = xml.NFe.infNFe.emit.enderEmit.nro;
                        entrada.MunicipioFornecedor = xml.NFe.infNFe.emit.enderEmit.xMun;
                        entrada.BairroFornecedor = xml.NFe.infNFe.emit.enderEmit.xBairro;
                        entrada.UfFornecedor = xml.NFe.infNFe.emit.enderEmit.UF.ToString();
                        entrada.CepFornecedor = xml.NFe.infNFe.emit.enderEmit.CEP;
                        entrada.TelefoneFornecedor = xml.NFe.infNFe.emit.enderEmit.fone.ToString();
                        entrada.ItensEntrada = produtos;
                        entrada.StatusEntrada = Compartilhado.Enums.StatusEntradaEnum.Validando;

                        var retorno = await _entradaAppService.CriarPorNf(entrada);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
            return Ok(true);
        }
        catch (Exception ex)
        {
            return Ok(ex);
        }
    }

O problema é que ao tentar utilizar o método CarregarDeArquivoXml(_caminhoXml + arq.FileName) o código cai na seguinte exceção: "Serialization and deserialization of 'System.Type' instances are not supported and should be avoided since they can lead to security issues. Path: $.TargetSite.DeclaringType."

Peço que me deem sugestões de como resolver este problema.

2
  • Se o erro acontece em CarregarDeArquivoXml, por que não colocou o código deste método? 1/02/2022 às 17:32
  • este método é dos metadados do c#, ele vem da biblioteca que estou usando, não tenho a implementação dele
    – wrafanunes
    1/02/2022 às 17:42

1 Resposta 1

0

Consegui resolver, o problema era que o upload estava salvando o arquivo em uma pasta do próprio sistema, isso gerava problemas de segurança e impedia a serialização, eu criei um método para salvar em uma pasta de testes que criei localmente, segue:

private readonly string _caminho;
public EntradaController(IMediatorHandler handler,
                                INotificationHandler<DomainNotification> notification, IEntradaQueries queries) : base(handler, notification)
    {
        _queries = queries;
        _caminho = @"C:\teste\"; // desenvolvimento
    }
private async Task<IFormFileCollection> SalvarArquivoXml()
    {
        try
        {
            IFormFileCollection forms = Request.Form.Files;
            if (forms.Count > 0 || forms != null)
            {
                try
                {
                    foreach (var form in forms)
                    {
                        using var fileStream = new FileStream(_caminho + form.FileName, FileMode.Create);
                        await form.CopyToAsync(fileStream);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
            return forms;
        }
        catch (Exception e)
        {
            Console.Write(e);
            throw;
        }
    }

Também alterei a linha que criava a IFormFileCollection para IFormFileCollection files = await SalvarArquivoXml();

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .