Pregunta

In my controller classes I have a lot of methods which output properly formatted JSON data. All of them perform a database query. E.g.

// GET api/User
public IEnumerable<Object> GetUsers()
{
    var query = from user in db.Users
                orderby user.Name
                select new { Name = user.Name};

    return query.AsEnumerable<Object>();
}

Now I'd like to return the properties of one of my classes.

public IEnumerable<Object> GetProperties()
{
    return typeof(MyClass)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Select(p => p.Name).ToList();
}

However, instead of outputing JSON Entity Framework gives me some XML like

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <string>Property1</string>
    <string>Property2</string>
</ArrayOfstring>

I've tried to convert the output in the controller method.

public string GetProperties()
{
    var results = typeof(ComplexInfo)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Select(p => p.Name).ToList();
    return JsonConvert.SerializeObject(results, Formatting.Indented,
        new JsonSerializerSettings {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        });
}

Unfortunately it's still outputting XML.

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[
  "Property1",
  "Property2",
]</string>

How can I make sure to retrieve JSON objects from the controller?

¿Fue útil?

Solución

I had also faced same issue in my web api. solution is, you have to remove XmlFormatter from WebApiConfig.

 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);
 }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top