Using Protobuf-Net Media Formatter with Web API 2

The example shows how to setup a Web API 2 service using Protobuf-Net as it Media Formatter and a HttpClient which gets and deserializes the response using Protobuf-Net.

Protobuf is choosen because it’s the fastest Media Formatter at present.


Web API 2 Server

The server is just a basic Web API MVC 5 project. WebApiContrib.Formatting.ProtoBuf is then added using NuGet.


A simple Protobuf-Net Dto class is required for the client response. This uses the standard Protobuf-Net attributes.

using ProtoBuf;

namespace WebAPiProtobuf.Models
	public class ProtobufModelDto
            public int Id { get; set; }
            public string Name { get; set; }
            public string StringValue { get; set; }    

The Formatter is then added to the Web API configuration: config.Formatters.Add(new ProtoBufFormatter());

using System.Web.Http;
using WebApiContrib.Formatting;

namespace WebAPiProtobuf
    public static class WebApiConfig
        public static void Register(HttpConfiguration config)
            // Web API configuration and services

            // Web API routes

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

            config.Formatters.Add(new ProtoBufFormatter());

This is then used in the get method. If ‘application/x-protobuf’ is sent in the Request Header, the content will be returned in a protobuf binary serialization, otherwise per default, a json object is returned.

using System.Collections.Generic;
using System.Web.Http;
using WebAPiProtobuf.Models;

namespace WebAPiProtobuf.Controllers
    public class ValuesController : ApiController
        // GET api/values/5
        public ProtobufModelDto Get(int id)
            return new ProtobufModelDto(){Id =1,Name="HelloWorld", StringValue = "My first Protobuf web api service"};


The HttpClient is implemented in a simple console application. The Web Api Client and WebApiContrib.Formatting.ProtoBuf NuGet packages are added to the application.

The Accept Header ‘application/x-protobuf’ is added to the client and the MediaFormatter ‘ProtoBufFormatter’ is added to the response object, otherwise it cannot be deserialized.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using WebApiContrib.Formatting;
using WebAPiProtobuf.Models;

namespace WebClientProtobuf
    class Program
        static void Main(string[] args)
            var client = new HttpClient {BaseAddress = new Uri("http://localhost:49916/")};
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));

            HttpResponseMessage response = client.GetAsync("api/Values/4").Result; 
            if (response.IsSuccessStatusCode)
                // Parse the response body. Blocking!
                var p = response.Content.ReadAsAsync<ProtobufModelDto>(new[] { new ProtoBufFormatter()}).Result;
                Console.WriteLine("{0}\t{1};\t{2}", p.Name, p.StringValue, p.Id);               
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);


The object is then displayed in the console.

The Protobuf-Net Media Formatter is very easy to use and gives you maximum performance for a backend service. (Size of data content and speed of serialization)



  1. Doron · · Reply

    Hi I was trying that with a XMLHttpRequest from a web client, and it says in Fiddler that he brings me back a JSON.
    Do you have an example for using is with a web client requests?


  2. Jay Shah · · Reply

    It is giving me error of ArrayTypeMismatch in config.Formatters.Add(new ProtoBufFormatter()); runtime. Any suggestion ?

    1. Are your protobuf ids correct?

  3. Jay Shah · · Reply

    Hi, Thanks for your prompt reply. I did not get by protobuf Ids correct ? where should i check ? Thanks in advance.

    Insallted packages

  4. Jay Shah · · Reply
  5. Jay Shah · · Reply

    Microsoft.AspNet.WebApi.Client” version=”4.0.30506.0″
    Microsoft.Net.Http” version=”2.0.20710.0″
    MVC5″ version=”5.2.3″
    Newtonsoft.Json” version=”4.5.11″
    protobuf-net” version=”″
    WEBAPI2″ version=”2.2.0″
    WebApiContrib.Formatting.ProtoBuf” version=”″

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: