Lựa chọn 1 - Tạo mô hình mới
Thay vì trả lại
public IEnumerable<Person> Get()
trở
public People Get()
nơi
public class People {
public IEnumerable<Person> People {get; set;}
}
Lựa chọn 2 - trở lại động
Thay vì trả lại
public IEnumerable<Person> Get()
trở
public dynamic Get() {
IEnumerable<Person> p = //initialize to something;
return new {people = p};
}
Tùy chọn 3 - sửa đổi JsonMediaTypeFormatter
Bạn vẫn có thể quay trở lại
public IEnumerable<Person> Get()
nhưng thêm lớp sau:
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);
}
}
bây giờ trong WebApiConfig chỉ đăng ký định dạng mới thay vì cũ JSON một:
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());
Nguồn
2013-01-22 04:40:01