Wariant 1 - Tworzenie nowego modelu
Zamiast powrocie
public IEnumerable<Person> Get()
powrót
public People Get()
gdzie
public class People {
public IEnumerable<Person> People {get; set;}
}
Wariant 2 - powrót dynamiczny
Zamiast powrocie
public IEnumerable<Person> Get()
powrót
public dynamic Get() {
IEnumerable<Person> p = //initialize to something;
return new {people = p};
}
Opcja 3 - modyfikować JsonMediaTypeFormatter
Nadal można powrócić
public IEnumerable<Person> Get()
jednak dodać następujące klasy:
public class PeopleAwareJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if ((typeof (IEnumerable<People>).IsAssignableFrom(type)))
{
value = new {people = value};
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
teraz w WebApiConfig tylko zarejestrować nowego formatowania zamiast starego JSON jednym:
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());