I have a Web API 2 project and my WebApiConfig
looks like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config
.MapHttpAttributeRoutes();
config
.Formatters
.JsonFormatter
.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
}
}
This works fine, but I want the json to be parsed 'Mongo DB style' so automatically get serialization of ObjectIDs, so I can use attributes like [BsonElement("name")]
on properties in my model classes and so on.
I looked around and found this article http://odetocode.com/blogs/scott/archive/2013/09/30/custom-serialization-with-json-net-webapi-and-bsondocument.aspx but it seems a bit outdated and I cannot get it to work.
I'm pretty stuck for the moment, help much appreciated.
You need to implement and register a custom media formatter. Basically, you need to do this:
MediaTypeFormatter
(asynchronous read/write implementation) or BufferedMediaTypeFormatter
(synchronous read/write implemetation)
CanWriteType
+ WriteToStream
and/or CanreadType
+ ReadFromStream
Take into account that the formatter will be used:
Content-Type
header (this is the Read part of your implementation)Accept
header (this is the write part of your implementation)You can have a look at these samples, or google for "Web API custom media formatters" to get more info and samples:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments