C# 未能在 Web API 中序列化响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12641386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:59:18  来源:igfitidea点击:

failed to serialize the response in Web API

c#serializationasp.net-web-api

提问by Tamal kanti Dey

I was working on ASP.NET MVC web API, I'm having this error:

我正在处理 ASP.NET MVC Web API,我遇到了这个错误:

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

“ObjectContent`1”类型未能序列化内容类型“application/xml”的响应主体;字符集=utf-8'。

My controller is:

我的控制器是:

public Employee GetEmployees()
{
    Employee employees = db.Employees.First();
    return employees;
}

why I m getting this error?

为什么我收到这个错误?

回答by Julito Avellaneda

in your global.asax file, in the Application_start() method add this line:

在 global.asax 文件中,在 Application_start() 方法中添加以下行:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

I hope that helps you!

我希望对你有帮助!

回答by aamir sajjad

hmmm, Following may help.

嗯,以下可能会有所帮助。

I was getting the same exception, and in my case I was passing the actual poco entity created for entity code first. Since, it contains relation with other entities, I just created the viewmapper/dto entity on top of it to return.

我遇到了同样的异常,在我的情况下,我首先传递了为实体代码创建的实际 poco 实体。因为它包含与其他实体的关系,所以我只是在它上面创建了 viewmapper/dto 实体来返回。

It works fine now.

它现在工作正常。

Poco Entity:

Poco实体:

public class Tag
{
public int Id{get;set;}
public string Title{get;set;}
public IList<Location> Locations{get;set;}
}

ViewMapper/Dto

视图映射器/Dto

public class TagResultsViewMapper
{
public int Id{get;set;}
public string Title{get;set;}
//just remove the following relationship 
//public IList<Location> Locations{get;set;}
}

回答by Sadjad Khazaie

Put this in constructor. Hope this solve the problem:

把它放在构造函数中。希望这能解决问题:

    public MyController()
    {

        db.Configuration.ProxyCreationEnabled = false;
    }

回答by Ray Suelzer

I found two solutions to this. The first and easiest to implement is to change any IEnumerables, ICollections to a type of List. The WebAPI can serialize this objects, it however cannot serialize interface types.

我找到了两个解决方案。第一个也是最容易实现的是将任何 IEnumerables、ICollections 更改为 List 类型。WebAPI 可以序列化此对象,但不能序列化接口类型。

public class Store
{

  [StringLength(5)]
    public string Zip5 { get; set; }

    public virtual List<StoreReport> StoreReports { get; set; }  //use a list here
 }

The other option is to not use the native JSON serializer and run this override in the Register method of the WebApi Config:

另一种选择是不使用本机 JSON 序列化程序并在 WebApi Config 的 Register 方法中运行此覆盖:

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

回答by taynguyen

I got the same problem. And I solved it. I put the default constructor to the DTO class.

我遇到了同样的问题。我解决了它。我将默认构造函数放在 DTO 类中。

Ex:

前任:

public class User
{
    public User()
    {
    }
}

Hope it work with you!

希望它与你合作!

回答by Julito Avellaneda

please check the web api documentation for this problem, Handling Circular Object References

请查看 web api 文档以了解此问题,处理循环对象引用

Regards

问候

回答by Julito Avellaneda

but if you found this problem with other entities/classes, you have to create a new DTO for each class, and if you have a lot of them, you can find a problem, also I think that create a DTO only for solving this problem is no the best way...

但是如果你发现其他实体/类有这个问题,你必须为每个类创建一个新的DTO,如果你有很多,你可以找到问题,我认为创建一个DTO只是为了解决这个问题不是最好的方法...

Did you try this?

你试过这个吗?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
Newtonsoft.Json.PreserveReferencesHandling.All;

Regards

问候

回答by om471987

Solution is simple.

解决方法很简单。

After LINQ query add .ToList() (or ToDictionary if need).

在 LINQ 查询后添加 .ToList() (或 ToDictionary 如果需要)。

It will do eager loading than lazy loading of the data

它会比延迟加载数据进行急切加载

回答by Zane

For me this was a problem with circular referencing.

对我来说,这是循环引用的问题。

The accepted answer did not work for me because it only changes the behaviour of the JSON formatter, but I was getting XML when I called the service from the browser.

接受的答案对我不起作用,因为它只改变了 JSON 格式化程序的行为,但是当我从浏览器调用服务时,我得到了 XML。

To fix this, I switched off XML and forced only JSON to be returned.

为了解决这个问题,我关闭了 XML 并强制只返回 JSON。

In the Global.asax file, put the following lines at the top of your Application_Start method:

在 Global.asax 文件中,将以下行放在 Application_Start 方法的顶部:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Now only JSON results will be returned. If you need XML results, you will need to find a different solution.

现在只会返回 JSON 结果。如果您需要 XML 结果,您将需要找到不同的解决方案。

回答by Mohamed.Abdo

** this bug occur when calling from request web api/wcf/... from client side, but as side effect, you will need to include depending relations by include keyword. **

** 从客户端从请求 web api/wcf/... 调用时会发生此错误,但作为副作用,您需要通过 include 关键字包含依赖关系。**

public CustomerPortalContext()
            : base("Name=CustomerPortalContext")
        {
            base.Configuration.ProxyCreationEnabled = false;
        }