且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法使用 Json 序列化 Web API 中的响应

更新时间:2023-02-15 09:25:13

当涉及到从 Web Api(或任何其他与此相关的 Web 服务)返回数据给消费者时,我强烈建议不要将返回的实体传回从数据库.使用模型更可靠和可维护,您可以在其中控制数据的外观而不是数据库.这样你就不必在 WebApiConfig 中过多地处理格式化程序.您可以创建一个 UserModel ,它具有子模型作为属性,并摆脱返回对象中的引用循环.这让序列化器更快乐.

When it comes to returning data back to the consumer from Web Api (or any other web service for that matter), I highly recommend not passing back entities that come from a database. It is much more reliable and maintainable to use Models in which you have control of what the data looks like and not the database. That way you don't have to mess around with the formatters so much in the WebApiConfig. You can just create a UserModel that has child Models as properties and get rid of the reference loops in the return objects. That makes the serializer much happier.

此外,如果您只是在请求中指定接受"标头,则通常不需要删除格式化程序或支持的媒体类型.玩弄这些东西有时会让事情变得更加混乱.

Also, it isn't necessary to remove formatters or supported media types typically if you are just specifying the "Accepts" header in the request. Playing around with that stuff can sometimes make things more confusing.

示例:

public class UserModel {
    public string Name {get;set;}
    public string Age {get;set;}
    // Other properties here that do not reference another UserModel class.
}