¿Cómo consigo ASP.NET Web API para devolver JSON en lugar de XML usando Chrome?


Usando el nuevo ASP.NET Web API , en Chrome Estoy viendo XML - ¿cómo puedo cambiarlo para solicitar JSON para que pueda verlo en el navegador? Creo que es solo parte de los encabezados de solicitud, ¿estoy en lo correcto?

Author: DanielV, 2012-03-24

29 answers

Solo añado lo siguiente en la clase App_Start / WebApiConfig.cs en mi proyecto MVC Web API.

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );

Eso asegura que obtiene json en la mayoría de las consultas, pero puede obtener xml cuando envía text/xml.

Si necesita tener la respuesta Content-Type como application/json por favor revise La respuesta de Todd a continuación.

NameSpace está usando System.Net.Http.Headers;

 1553
Author: Felipe Leusin,
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-07-03 19:42:06

Si hace esto en el WebApiConfig obtendrá JSON de forma predeterminada, pero aún así le permitirá devolver XML si pasa text/xml como el encabezado request Accept

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

Si no está utilizando el tipo de proyecto MVC y por lo tanto no tenía esta clase para empezar, consulte esta respuesta para obtener detalles sobre cómo incorporarla.

 477
Author: Glenn Slaven,
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-05-23 12:34:53

Me gusta El enfoque de Felipe Leusin mejor: asegúrese de que los navegadores obtengan JSON sin comprometer la negociación de contenido de los clientes que realmente desean XML. La única pieza que me faltaba era que los encabezados de respuesta todavía contenían content-type: text / html. ¿Por qué era un problema? Porque uso la extensión JSON Formatter Chrome, que inspecciona el tipo de contenido, y no consigo el formato bonito al que estoy acostumbrado. Arreglé eso con un formateador personalizado simple que acepta texto / html solicitudes y devoluciones application / json responses:

public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
    public BrowserJsonFormatter() {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        this.SerializerSettings.Formatting = Formatting.Indented;
    }

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
}

Regístrate así:

config.Formatters.Add(new BrowserJsonFormatter());
 283
Author: Todd Menier,
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-05-23 12:10:47

Usando RequestHeaderMapping funciona aún mejor, porque también establece el Content-Type = application/json en el encabezado de la respuesta, lo que permite a Firefox (con el complemento JsonView) formatear la respuesta como JSON.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept", 
                              "text/html",
                              StringComparison.InvariantCultureIgnoreCase,
                              true, 
                              "application/json"));
 242
Author: dmit77,
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-06-19 12:50:28

MVC4 Consejo rápido #3-Eliminación del formateador XML de ASP.Net API web

{[3] {} En[2]} añadir la línea:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

Así:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    BundleTable.Bundles.RegisterTemplateBundles();
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
 174
Author: Yakir Manor,
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
2013-08-06 13:00:36

En el WebApiConfig.cs , añadir al final de la función Register:

// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

Source .

 103
Author: Michael Vashchinsky,
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
2016-12-08 20:18:56

En el Global.asax Estoy usando el siguiente código. Mi URI para obtener JSON es http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}
 88
Author: Diganta Kumar,
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
2016-12-08 20:51:49

Echa un vistazo a la negociación de contenido en la WebAPI. Estos (Parte 1 & Parte 2 ) maravillosamente detalladas y exhaustivas entradas de blog explican cómo funciona.

En resumen, tiene razón, y solo necesita establecer los encabezados de solicitud Accept o Content-Type. Dado que su Acción no está codificada para devolver un formato específico, puede establecer Accept: application/json.

 48
Author: Aaron Daniels,
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-09 19:20:13

Como la pregunta es específica de Chrome, puede obtener la extensión Postman que le permite establecer el tipo de contenido de la solicitud.

Cartero

 39
Author: Chris S,
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
2013-09-27 10:40:29

Una opción rápida es utilizar la especialización MediaTypeMapping. Aquí hay un ejemplo de uso de QueryStringMapping en el evento Application_Start:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("a", "b", "application/json"));

Ahora cada vez que la url contiene el querystring ?a = b en este caso, la respuesta Json se mostrará en el navegador.

 31
Author: suhair,
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-03-27 05:08:37

Este código hace que json sea mi predeterminado y me permite usar el formato XML también. Voy a añadir el xml=true.

GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Gracias a todos!

 28
Author: jayson.centeno,
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
2016-07-11 15:17:26

No utilice su navegador para probar su API.

En su lugar, intente usar un cliente HTTP que le permita especificar su solicitud, como CURL o incluso Fiddler.

El problema con este problema está en el cliente, no en la API. La API web se comporta correctamente, de acuerdo con la solicitud del navegador.

 18
Author: dmyoko,
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
2014-04-25 21:26:14

La mayoría de las respuestas anteriores tienen perfecto sentido. Dado que está viendo que los datos se formatean en formato XML, eso significa que se aplica XML formatter, por lo que puede ver el formato JSON simplemente eliminando el XMLFormatter del parámetro HttpConfiguration como

public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );                
            config.Formatters.Remove(config.Formatters.XmlFormatter);                
            config.EnableSystemDiagnosticsTracing();
        }

Dado que JSON es el formato predeterminado

 10
Author: pavan kumar,
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-04-13 06:26:19

Usé un filtro de acción global para eliminar Accept: application/xml cuando el encabezado User-Agent contiene "Chrome":

internal class RemoveXmlForGoogleChromeFilter : IActionFilter
{
    public bool AllowMultiple
    {
        get { return false; }
    }

    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(
        HttpActionContext actionContext,
        CancellationToken cancellationToken,
        Func<Task<HttpResponseMessage>> continuation)
    {
        var userAgent = actionContext.Request.Headers.UserAgent.ToString();
        if (userAgent.Contains("Chrome"))
        {
            var acceptHeaders = actionContext.Request.Headers.Accept;
            var header =
                acceptHeaders.SingleOrDefault(
                    x => x.MediaType.Contains("application/xml"));
            acceptHeaders.Remove(header);
        }

        return await continuation();
    }
}

Parece funcionar.

 8
Author: Roger Lipscombe,
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
2013-06-23 14:47:02

Me pareció que la aplicación Chrome "Cliente REST avanzado" excelente para trabajar con servicios REST. Puede establecer el Content-Type en application/json entre otras cosas: Cliente REST avanzado

 6
Author: Mike Rowley,
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
2015-09-30 07:42:04

Devolver el formato correcto lo hace el formateador de tipo medio. Como otros han mencionado, puedes hacer esto en la clase WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        // Configure Web API to return JSON
        config.Formatters.JsonFormatter
        .SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

        ...
    }
}

Para obtener más información, consulte:

En caso de que sus acciones devuelvan XML (que es el caso por defecto) y solo necesite un método específico para devolver JSON, puede usar un ActionFilterAttribute y aplicarlo a ese método específico acto.

Atributo de Filtro:

public class JsonOutputAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
        var value = content.Value;
        Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];

        var httpResponseMsg = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            RequestMessage = actionExecutedContext.Request,
            Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
        };

        actionExecutedContext.Response = httpResponseMsg;
        base.OnActionExecuted(actionExecutedContext);
    }
}

Aplicación a la acción:

[JsonOutput]
public IEnumerable<Person> GetPersons()
{
    return _repository.AllPersons(); // the returned output will be in JSON
}

Tenga en cuenta que puede omitir la palabra Attribute en la decoración de la acción y usar solo [JsonOutput] en lugar de [JsonOutputAttribute].

 5
Author: Stacked,
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
2016-12-09 16:27:58

No me queda claro por qué hay toda esta complejidad en la respuesta. Seguro que hay muchas maneras de hacer esto, con QueryStrings, encabezados y opciones... pero lo que creo que es la mejor práctica es simple. Usted solicita una URL simple (ej: http://yourstartup.com/api/cars) y a cambio obtiene JSON. Se obtiene JSON con el encabezado de respuesta adecuado:

Content-Type: application/json

Al buscar una respuesta a esta misma pregunta, encontré este hilo, y tuve que seguir adelante porque esta respuesta aceptada no funciona exactamente. Me encontré una respuesta que creo que es demasiado simple para no ser la mejor:

Establecer el formateador WebAPI predeterminado

Voy a añadir mi consejo aquí también.

WebApiConfig.cs

namespace com.yourstartup
{
  using ...;
  using System.Net.Http.Formatting;
  ...
  config.Formatters.Clear(); //because there are defaults of XML..
  config.Formatters.Add(new JsonMediaTypeFormatter());
}

Tengo una pregunta de dónde vienen los valores predeterminados (al menos los que estoy viendo). Son valores predeterminados de. NET, o tal vez creados en otro lugar (por otra persona en mi proyecto). De todos modos, espero que esto ayude.

 4
Author: Nick,
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-05-23 10:31:37

Aquí hay una solución similar a jayson.centeno y otras respuestas, pero usando la extensión incorporada de System.Net.Http.Formatting.

public static void Register(HttpConfiguration config)
{
    // add support for the 'format' query param
    // cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx
    config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
    config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");

    // ... additional configuration
 }

La solución estaba orientada principalmente a soportar $format para OData en las primeras versiones de WebAPI, pero también se aplica a la implementación que no es OData, y devuelve Content-Type: application/json; charset=utf-8 encabezado en la respuesta.

Le permite virar &$format=json o &$format=xml al final de su uri cuando realiza pruebas con un navegador. No interfiere con otras expectativas comportamiento al usar un cliente que no es navegador donde puede establecer sus propios encabezados.

 3
Author: mdisibio,
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-05-23 12:18:27

Simplemente cambia el App_Start/WebApiConfig.cs así:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        //Below formatter is used for returning the Json result.
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        //Default route
        config.Routes.MapHttpRoute(
           name: "ApiControllerOnly",
           routeTemplate: "api/{controller}"
       );
    }
 2
Author: vaheeds,
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
2016-02-08 05:03:12

Según la última versión de ASP.net WebAPI 2,

Bajo WebApiConfig.cs, esto funcionará

config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
 2
Author: A.T.,
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
2016-10-27 10:26:57

Simplemente agregue esas dos líneas de código en su WebApiConfig clase

public static class WebApiConfig
{
     public static void Register(HttpConfiguration config)
     {
          //add this two line 
          config.Formatters.Clear();
          config.Formatters.Add(new JsonMediaTypeFormatter());


          ............................
      }
}
 2
Author: Md. Sabbir Ahamed,
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
2016-11-10 11:11:24
        config.Formatters.Remove(config.Formatters.XmlFormatter);
 2
Author: Gaurav Dubey,
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-07-01 04:31:36

Desde MSDN Crear una Aplicación de Una Sola Página con ASP.NET y AngularJS (unos 41 minutos en).

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // ... possible routing etc.

        // Setup to return json and camelcase it!
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    }

Debe ser actual, lo probé y funcionó.

 1
Author: lko,
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
2014-09-30 19:19:10

Ha pasado algún tiempo desde que se hizo esta pregunta (y se respondió), pero otra opción es anular el encabezado Accept en el servidor durante el procesamiento de solicitudes utilizando un MessageHandler como se muestra a continuación:

public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
    {
        var someOtherCondition = false;
        var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
        if (someOtherCondition && accHeader.Contains("application/xml"))
        {
            request.Headers.Remove("Accept");
            request.Headers.Add("Accept", "application/json");
        }
        return await base.SendAsync(request, cancellationToken);
    }
}

Donde someOtherCondition puede ser cualquier cosa, incluido el tipo de navegador, etc. Esto sería para casos condicionales en los que solo a veces queremos anular la negociación de contenido predeterminada. De lo contrario, según otras respuestas, simplemente eliminaría un formateador innecesario del configuración.

Tendrás que registrarlo, por supuesto. Puedes hacer esto globalmente:

  public static void Register(HttpConfiguration config) {
      config.MessageHandlers.Add(new ForceableContentTypeDelegationHandler());
  }

O ruta por ruta:

config.Routes.MapHttpRoute(
   name: "SpecialContentRoute",
   routeTemplate: "api/someUrlThatNeedsSpecialTreatment/{id}",
   defaults: new { controller = "SpecialTreatment" id = RouteParameter.Optional },
   constraints: null,
   handler: new ForceableContentTypeDelegationHandler()
);

Y dado que este es un manejador de mensajes, se ejecutará tanto en los extremos de solicitud como de respuesta de la canalización, de manera similar a un HttpModule. Así que usted podría fácilmente reconocer la anulación con un encabezado personalizado:

public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
    {
        var wasForced = false;
        var someOtherCondition = false;
        var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
        if (someOtherCondition && accHeader.Contains("application/xml"))
        {
            request.Headers.Remove("Accept");
            request.Headers.Add("Accept", "application/json");
            wasForced = true;
        }

        var response =  await base.SendAsync(request, cancellationToken);
        if (wasForced){
          response.Headers.Add("X-ForcedContent", "We overrode your content prefs, sorry");
        }
        return response;
    }
}
 1
Author: rism,
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
2015-12-06 07:44:25

Aquí está la forma más fácil que he utilizado en mis aplicaciones. Añadir a continuación 3 líneas de código en App_Start\\WebApiConfig.cs en Register función

    var formatters = GlobalConfiguration.Configuration.Formatters;

    formatters.Remove(formatters.XmlFormatter);

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

Asp.net web API automáticamente serializará el objeto devuelto a JSON y a medida que se agregue application/json en el encabezado, el navegador o el receptor entenderán que está devolviendo el resultado JSON.

 1
Author: Vikas Bansal,
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
2016-05-28 10:49:51

WebApiConfig es el lugar en el que puede configurar si desea generar la salida en json o xml. por defecto es xml. en la función register podemos utilizar los formateadores HttpConfiguration para dar formato a la salida . System.Net.Http.Headers => MediaTypeHeaderValue("text/html") es necesario para obtener la salida en formato json. introduzca la descripción de la imagen aquí

 0
Author: Parag,
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
2016-09-25 00:13:10

Usted puede utilizar como abajo:

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
 0
Author: Akshay Kapoor,
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-04-11 10:21:38

Usando la respuesta de Felipe Leusin durante años, después de una reciente actualización de las bibliotecas centrales y de Json.Net, Me encontré con un System.MissingMethodException: SupportedMediaTypes. La solución en mi caso, espero que sea útil para otros que experimentan la misma excepción inesperada, es instalar System.Net.Http. NuGet aparentemente lo elimina en algunas circunstancias. Después de una instalación manual, el problema se resolvió.

 0
Author: Charles Burns,
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-04-13 19:42:40

Me sorprende ver tantas respuestas que requieren codificación para cambiar un solo caso de uso (GET) en una API en lugar de usar una herramienta adecuada lo que debe instalarse una vez y puede usarse para cualquier API (propia o de terceros) y todos los casos de uso.

Así que la buena respuesta es:

  1. Si solo desea solicitar json u otro tipo de contenido, instale Requestly o una herramienta similar y modifique el encabezado Accept.
  2. Si quieres usar POST también y tener muy bien formato json, xml, etc. utilice una extensión de prueba API adecuada como Postman o ARC.
 -3
Author: user3285954,
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-11-30 23:01:52