Reputation: 6772
We are trying to implement MessagePack on our Web API. However I am having trouble finding a reliable up-to-date formatter. I found the WebApiContrib.Formatting.MsgPack formatter but the last update was in 2014 and when I try using it it throws "Method not found" exception.
I also looked at an example here but the code contains some method references that are no longer present in the nuget package.
There seems to be an updated ASP.NET Core library with a set of formatters but we are not looking to move to Core any time soon.
Does someone have a tip for a reliable formatter for MessagePack that would do the trick?
Upvotes: 1
Views: 1806
Reputation: 31282
Implementing custom Media Type Formatter is pretty easy task if you have all serialization/deserialization code. So if you can't find suitable solution, you could implement your own. Here is working sample:
public class MessagePackFormatter : MediaTypeFormatter
{
public MessagePackFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-msgpack"));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (writeStream == null)
{
throw new ArgumentNullException(nameof(writeStream));
}
MessagePackSerializer.NonGeneric.Serialize(type, writeStream, value, ContractlessStandardResolver.Instance);
return Task.FromResult(0);
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (readStream == null)
{
throw new ArgumentNullException(nameof(readStream));
}
var value = MessagePackSerializer.NonGeneric.Deserialize(type, readStream, ContractlessStandardResolver.Instance);
return Task.FromResult(value);
}
}
As you see it's very thin and just invokes MessagePackSerializer.NonGeneric
class for serialization/deserialization. I'd suggest starting using such simple formatter and if you encounter some problems with it for specific cases, just tune the code to fix the issues. You could also examine existing implementation for .Net Core for handling some corner cases.
Upvotes: 1