网页API 2 XML序列化无视MetadataType [英] Web API 2 XML Serialization is ignoring MetadataType

查看:203
本文介绍了网页API 2 XML序列化无视MetadataType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过实体框架5 的,类似于生成一个简单的类:

I have a simple class that is generated by Entity Framework 5, similar to:

public partial class Car
{
   public string Model {get; set;}
   // other properties follow...
}

我创建了一个伴侣类(以保持不被覆盖这些东西)和一个伙伴级来保存元数据:

I have created a companion class (to keep these things from being overwritten) and a "buddy class" to hold the metadata::

[MetadataType(typeof(CarMetadata))]
public partial class Car { }

[DataContract("Automobile")]
public partial class CarMetadata
{
   [DataMember]
   public string Model {get; set;}
}

当我在运行应用程序的帮助页面我的车的帮助/原料药/ GET-API的汽车模型的给我这个错误:

When I run the application the Help page for my car at Help/Api/GET-api-car-model gives me this error:

An exception has occurred while using the formatter 'XmlMediaTypeFormatter'
to generate sample for media type 'application/xml'. 
Exception message: One or more errors occurred.

起脚的是,如果我把DataAnnotations的EF生成的类,它工作正常。这就像它忽略了哥们类......但JSON格式在翻译它作为预期。

The kicker is that if I put the DataAnnotations on the EF generated class it works fine. It's like it's ignoring the buddy class... but the JSON formatter is translating it as expected.

这给出正确的结果,在EF类,但它不能呆在那里,或者它覆盖:

This gives the correct result, on the EF class, but it can't stay there or it's overwritten:

[DataContract("Automobile")]
public partial class Car
{
   [DataMember]
   public string Model {get; set;}
   // other properties follow...
}

任何援助将大大AP preciated。

Any assistance would be greatly appreciated.

推荐答案

安东一样,我试图重复你的code,但它也为我工作。

Like Anton, I was trying to repeat your code , but it works for me too.

我的猜测是,你的模型比你把在岗的例子模型更加复杂,你必须引用循环和/或大量对象嵌套。

My guess is that you model is more complex than the example model you put in the post and you have referencing loops and/or a lot of object nesting.

尝试设置 config.Formatters.XmlFormatter.MaxDepth = 2 如果有很多嵌套的是present。 (如果它工作,调值,以满足您的需求)。

Try to set config.Formatters.XmlFormatter.MaxDepth = 2 if a lot of nesting is present. (If it works, tune the value to match your needs).

使用 [DataContract(IsReference = TRUE)] 如果类包含的对象树的任意点循环引用。

Use [DataContract(IsReference=true)] if the classes contains circular references in any point of the object tree.

使用两个如果这两个问题是present。结合
config.Formatters.XmlFormatter.UseXmlSerializer =真/假,以确保您尝试所有的选项。

Use both if both issues are present. Combine with config.Formatters.XmlFormatter.UseXmlSerializer = true/false to be sure you try all the options.

这是我最好的尝试。希望它帮助。

It's my best try. Hope it helps.

这篇关于网页API 2 XML序列化无视MetadataType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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