How to return data from a Webservice in XML format?

Asked

Viewed 985 times

0

I am using an example of webservice, but it is generating me an error stating that "Response' does not exist in the context Current", someone knows what could be wrong?

NOTE: Error runs at build time:

        Response.Write(resultado);
        Response.End();



using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Text;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using System.IO;
using System.Xml;


        public class DadosRetorno
    {
        [XmlAttribute("ativo")]
        public bool Ativo;

        [XmlElement("nome")]
        public string NomeCompleto { get; set; }

        [XmlElement("email")]
        public string EmailParticular { get; set; }

        [XmlElement("operacao")]
        public string OperacaoRealizada { get; set; }

        [XmlElement("parcelas")]
        public string QuantidadeParcelas { get; set; }
    }



    [WebMethod(Description = "retornar dados no formato xml")]
    public string GetConsultaDados()
    {
        //Lista de usuários
        List<DadosRetorno> DadosConsulta = new List<DadosRetorno>();

        //Populando a lista de usuários
        for (int i = 1; i <= Convert.ToInt32(3); i++)
        {
            DadosRetorno Dados = new DadosRetorno();
            Dados.NomeCompleto = "Nome " + i;
            Dados.Ativo = true;
            Dados.EmailParticular = "email" + i + "@teste.com.br";
            Dados.OperacaoRealizada = "operacao " + i;
            Dados.QuantidadeParcelas = "qtdParcelas " + i;
            DadosConsulta.Add(Dados);
        }

        //Criar um Namespace para o XML
        XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();

        //Adicionar um item vazio para remover o Namespace xsi, xsd do XML
        xmlNamespace.Add("", "");

        //Obviamente o XmlSerializerNamespaces serve para adicionar um novo namespace também.
        //A linha abaixo vai adicionar xsd no XML
        xmlNamespace.Add("namespace", "value");

        //Configurações do XML
        XmlWriterSettings settings = new XmlWriterSettings();

        //A linha abaixo omite a declaração do XML: <?xml version="1.0" encoding="utf-8"?>
        settings.OmitXmlDeclaration = true;

        //Definir a codificação do XML
        settings.Encoding = Encoding.UTF8;

        //Identar o XML automaticamente
        settings.Indent = true;

        //MemoryStream para colocar o XML em memória
        MemoryStream stream = new MemoryStream();

        //Usar o Create do XmlTextWriter para aplicar as configurações no XML
        XmlWriter writer = XmlTextWriter.Create(stream, settings);

        //Definir o Type e o elemento raiz do XML (contatos)
        XmlSerializer ser = new XmlSerializer(DadosConsulta.GetType(), new XmlRootAttribute("DadosConsulta"));

        //Serializar o list, com o Namespace para o XmlWriter
        ser.Serialize(writer, DadosConsulta, xmlNamespace);

        //Converter o XmlWriter para string
        var buffer = new byte[stream.Length];
        stream.Read(buffer, 0, (int)stream.Length);
        string resultado = Encoding.UTF8.GetString(stream.ToArray());

        //Retornar o resultado
        Response.Write(resultado);
        Response.End();
    }
  • Missing a reference to Assembly System.Web.dll and/or a using for the namespace System.Web

  • I made the code change, already in the Using Sustem.Web plus this System.Web.dll what could be?

  • I refer to assemblies referenced by your project. But if you have a line using System.Web in this class and without build error, then you have the reference to Assembly. Does the error occur at runtime or build time? If build, point us to the line; if run, paste the full stack trace into the question.

  • Added to question where compile-time error occurs.

  • Really missing using for System.web. See if my answer is clear.

1 answer

1

The code has using for various Assembly namespaces System.Web.dll but lack using for the namespace where the class resides Response, in the case, System.Web.

Just add the following line next to the others using:

using System.Web;

Browser other questions tagged

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