ASP.NET Web API BSON Formatter

ASP.NET Web API includes JSON.NET which includes BSON Serializer so to support BSON format it is quite easy.

  1. Create a class called BSONFormatter and inherit from MediaTypeFormatter
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace WebAPI.Common.Formatter
{
     public class BsonFormatter : MediaTypeFormatter
    {
        public BsonFormatter()
        {
            SupportedMediaTypes
             .Add(new MediaTypeHeaderValue("application/bson"));
        }

        public MediaTypeHeaderValue MediaTypeHeaderValue
        {
            get 
           { 
               return new MediaTypeHeaderValue("application/bson"); 
            }
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
         }

2. Make sure you include following namespace

using

3. Override WriteToStreamAsync method, using BsonWriter by passing the stream and using JsonSerializer to serialize.

public override Task WriteToStreamAsync(Type type,
 object value, Stream writeStream, HttpContent content,
            TransportContext transportContext)
        {
            Task task = Task.Factory.StartNew(
                () =>
                    {
                        content.Headers.ContentType = MediaTypeHeaderValue;
                        var serializer = new JsonSerializer();

                        // serialize product to BSON
                        var writer = new BsonWriter(writeStream);
                        serializer.Serialize(writer, value);
                    });

            return task;
        }

4. Plugging it in Web.API pipeline.

  var config = new HttpSelfHostConfiguration("http://localhost:8080");
    ILifetimeScope container = GetContainerLifeTimeScope();
     config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "WebAPI/{controller}/{id}",
                defaults: new {id = RouteParameter.Optional}
                );

      config.Formatters.Add(new BsonFormatter());
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
      using (var server = new HttpSelfHostServer(config))
      {
                server.OpenAsync().Wait();
                Console.WriteLine("Press any key to terminate");
                Console.ReadLine();
        }

5. Bson Request/Response (in fiddler)

BsonRequest BsonResponse
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s