Cómo dejar que un archivo ASMX salga JSON


He creado un archivo ASMX con un código detrás del archivo. Está funcionando bien, pero está generando XML.

Sin embargo, lo necesito para generar JSON. La configuración de ResponseFormat no parece funcionar. Mi código detrás es:

[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
    public string[] UserDetails()
    {
        return new string[] { "abc", "def" };
    }
}
 60
Author: doekman, 2008-10-17

6 answers

Desde WebService devuelve XML incluso cuando ResponseFormat se establece en JSON :

Asegúrese de que la solicitud es una solicitud POST, no una GET. Scott Guthrie tiene un post explicando por qué.

Aunque está escrito específicamente para jQuery, esto también puede ser útil para usted:
Usar jQuery para Consumir ASP.NET JSON Web Services

 39
Author: Pavel Chuchuva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-10 05:40:55

Para recibir una cadena JSON pura, sin que esté envuelta en un XML, debe escribir la cadena JSON directamente en HttpResponse y cambiar el tipo de retorno WebMethod a void.

    [System.Web.Script.Services.ScriptService]
    public class WebServiceClass : System.Web.Services.WebService {
        [WebMethod]
        public void WebMethodName()
        {
            HttpContext.Current.Response.Write("{property: value}");
        }
    }
 51
Author: iCorrect,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-22 11:55:51

Esta es probablemente una vieja noticia por ahora, pero la magia parece ser:

  • [ScriptService] atributo en la clase de servicio web
  • [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] sobre el método
  • Content-type: application/json in request

Con esas piezas en su lugar, una solicitud GET es exitosa.

Para un HTTP POST

  • [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] sobre el método

Y en el lado del cliente (suponiendo que su webmethod se llama Nomodo, y toma un solo parámetro llamado searchString):

        $.ajax({
            url: "MyWebService.asmx/MethodName",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ searchString: q }),
            success: function (response) {                  
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ": " + jqXHR.responseText);
            }
        });
 14
Author: marc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-25 08:05:49

Un rápido gotcha que aprendí de la manera difícil (básicamente pasar 4 horas en Google), puede utilizar PageMethods en su archivo ASPX para devolver JSON (con el marcador [ScriptMethod ()]) para un método estático, sin embargo, si decide mover sus métodos estáticos a un archivo asmx, no puede ser un método estático.

Además, debe indicarle al servicio web Content-Type: application / json para recuperar JSON de la llamada (Estoy usando jQuery y los 3 Errores Que Debe Evitar Al Usar jQuery artículo fue muy esclarecedor-es del mismo sitio web mencionado en otra respuesta aquí).

 9
Author: Bryan Rehbein,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-21 21:19:34

¿Está llamando al servicio web desde el script del cliente o desde el lado del servidor?

Puede encontrar que enviar un encabezado de tipo de contenido al servidor le ayudará, por ejemplo,

'application / json; charset = utf-8'

En el lado del cliente, utilizo prototype client side library y hay un parámetro ContentType al hacer una llamada Ajax donde puede especificar esto. Creo que jQuery tiene un método getJSON.

 4
Author: bitsprint,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-17 10:38:54

Alternativa: Use un manejador HTTP genérico (.ashx) y utilice su biblioteca json favorita para serializar y deserializar manualmente su JSON.

He encontrado que el control completo sobre el manejo de una solicitud y la generación de una respuesta supera cualquier otra oferta de.NET para servicios web simples y RESTful.

 3
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-10 20:47:07