How to return a pure Json (without XML encapsulation) using webservice in C #

3

I have a webservice running locally , which performs queries directly in a database using a string parameter . Here is the result of the query:

ThesecondtimeIhaveajavascript(Jquery)applicationthatconsumeswebserviceviaAjax.AftersomeresearchIcametotheconclusionthattheproblemisXMLencapsulation,asI'mtryingtoconsumeJsonviaAjax.

Jqueryapplicationtryingtoconsumewbeservicec#viaAjax:

$("#btnConsultar").on("click",function(){

            var NTalao = $("#campoTalao").val();


            $.ajax({

                url: "...",
                type: "GET",
                contentType: "application/json",
                data: {"Talao": NTalao},
                success: function(data){
                    $("#resDIV").html(data);

                },
                error: function(){
                alert("Erro!");
                }
            });

        });

Webservice C # Returning Json Encapsulated:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public string Consultar(string _Talao)
    {

        Model1 cadastro = new Model1();
        clsRecibo recibo = new clsRecibo();

        var consulta = from a in cadastro.TB_Recibo
                       where a.Talao == _Talao
                       select a;


        foreach (var linha in consulta)
        {
            recibo.Talao = linha.Talao;
            recibo.Apresentante = linha.Apresentante;
            recibo.TipoServico = linha.TipoServico;
            recibo.Status = linha.Status;
            recibo.Obs = linha.Obs;
        }

        JavaScriptSerializer js = new JavaScriptSerializer();

        return js.Serialize(recibo);

    }

Base question: Is it possible to remove this XML encapsulation from the query? If not, can I query the application differently?

Thank you !!

    
asked by anonymous 02.11.2016 / 15:08

2 answers

1

Hudson, modify the method for void and return it as follows:

 HttpContext.Current.Response.ContentType = "application/json";
 HttpContext.Current.Response.Write(js.Serialize(recibo));
 HttpContext.Current.Response.End();
    
02.11.2016 / 16:51
2

For the ScriptMethod attribute to be interpreted, you need to ensure that the System.Web.Extensions module loads.

Two changes to the session system.web in your web.config are required:

<assemblies>
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>

<httpHandlers>
    <remove verb="*" path="*.asmx"/>
    <add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>

Original Post in SO in English.

    
02.11.2016 / 17:11