ASMX WebService Issues

0

When I send a JSON return and the text has an accent, JSON breaks.

  

Here is the request code on the Controller

$http.post("../backend/controller/SugestaoController.asmx/comboListarSugestoes", { empresa: $rootScope.login })
    .then(function (retorno) {
        //console.log("teste", retorno.data);
        $scope.listaSugestoes = retorno.data;
    }).catch(function (retorno) {
        alert("erro");
    })
    .finally(function () {
        $scope.mostrarLoader = false;
    });
  

Now the Server side, I'll just show how the submission is:

            JavaScriptSerializer js = new JavaScriptSerializer();
            String json = js.Serialize(retorno);
            context.Response.Clear();
            context.Response.Charset  = "utf-8";
            context.Response.ContentType = "application/json";
            //context.Response.ContentType = "text/html";
            context.Response.AddHeader("Content-Length", (json.Length).ToString());
            context.Response.Flush();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            context.Response.Write(json);
  

If you have accents, JSON goes like this:

[{nome:'felipe',funcao:'médico',idade:23
  

If it does not, it arrives normal

[{nome:'felipe',funcao:'medico',idade:23}]
    
asked by anonymous 29.07.2017 / 15:43

1 answer

1

I can not say for sure, but a guess: When reporting the response length on Content-Length, use the length in bytes, not the number of characters in the string. This can occur because the accented characters add a few bytes to the string. So instead of doing:

context.Response.AddHeader("Content-Length", (json.Length).ToString());

You do:

context.Response.AddHeader("Content-Length", Encoding.UTF8.GetBytes(json).Length.ToString());
    
29.07.2017 / 19:23