A couple of questions if you don't mind. The AbcFormatter class derives from BufferedMediaTypeFormatter. Is this required? Are there other options? I am assuming that this formatter is considered "appropriate" because of the 'SupportedMediaTypes'. I don't
totally understand CanReadType. What is 'IKeyValueModel'? For 'OnReadFromStream' is the Type that is passed in is the type of object. You don't use the type in this method so I am guessing that you could further check that the type is typeof(string) for your
class. Right? Since the class ReadAsSingleObjectPolicy is only used for the tests do I need it? What is its function?
Kevin Burton
Member
79 Points
66 Posts
Re: Custom content negotiation
Mar 14, 2012 07:36 PM|LINK
A couple of questions if you don't mind. The AbcFormatter class derives from BufferedMediaTypeFormatter. Is this required? Are there other options? I am assuming that this formatter is considered "appropriate" because of the 'SupportedMediaTypes'. I don't totally understand CanReadType. What is 'IKeyValueModel'? For 'OnReadFromStream' is the Type that is passed in is the type of object. You don't use the type in this method so I am guessing that you could further check that the type is typeof(string) for your class. Right? Since the class ReadAsSingleObjectPolicy is only used for the tests do I need it? What is its function?
I know it is used as an illustration but in reading http://www.tugberkugurlu.com/archive/asp-net-web-api-mediatypeformatters-with-mediatypemappings it seems that the two cases of JSON and XML are already handled with the default negotiation. So the default will handle either JSON or XML without the additions mentioned in this blog. Right?
So with your help I came up with the below class. Does this look right (Assuming that the stream contains XML)?
Thank you.
public class StreamFormatter : BufferedMediaTypeFormatter { public StreamFormatter() { this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream")); } protected override bool CanReadType(Type type) { if (type == typeof(IKeyValueModel)) { return false; } return true; } protected override bool CanWriteType(Type type) { return true; } protected override object OnReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) { XmlSerializer serializer = new XmlSerializer(type); return serializer.Deserialize(stream); } protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(stream, value); } }rkevinburton@charter.net
kevin_burton@baxter.com