我有一个Web API 2项目,我的WebApiConfig
样子是这样的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config
.MapHttpAttributeRoutes();
config
.Formatters
.JsonFormatter
.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
}
}
这可以正常工作,但是我希望将json解析为“ Mongo DB样式”,以便自动获取ObjectID的序列化,因此我可以[BsonElement("name")]
在模型类中使用诸如属性等属性。
我环顾四周,发现这篇文章http://odetocode.com/blogs/scott/archive/2013/09/30/custom-serialization-with-json-net-webapi-and-bsondocument.aspx,但似乎有点过时了我无法使它正常工作。
我暂时还很困,不胜感激。
您需要实现并注册自定义媒体格式化程序。基本上,您需要这样做:
MediaTypeFormatter
(异步读/写实现)或BufferedMediaTypeFormatter
(同步读/写实现) 派生一个类
CanWriteType
+WriteToStream
和/或CanreadType
+ReadFromStream
考虑到将使用格式化程序:
Content-Type
标头中指定媒体格式时解析接收到的数据(这是实现的“读取”部分)Accept
标头指定了媒体格式时,序列化返回的对象(这是实现的写部分)您可以查看以下示例,也可以在Google上查找“ Web API自定义媒体格式化程序”以获取更多信息和示例:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句