无法使用 Json 序列化 Web API 中的响应 [英] Failed to serialize the response in Web API with Json

查看:30
本文介绍了无法使用 Json 序列化 Web API 中的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET MVC 5 Web Api.我想咨询我所有的用户.

I am working with ASP.NET MVC 5 Web Api. I want consult all my users.

我写了 api/users 并且我收到了这个:

I wrote api/users and I receive this:

'ObjectContent`1' 类型未能序列化内容类型'application/json; charset=utf-8'的响应正文"

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

在 WebApiConfig 中,我已经添加了以下几行:

In WebApiConfig, already I added these lines:

HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

但是还是不行.

我的返回数据函数是这样的:

My function for return data is this:

public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}

推荐答案

当涉及到从 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.
}

这篇关于无法使用 Json 序列化 Web API 中的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆