Sunday, March 9, 2014

ASP.Net Web API with BSON

BSON is a binary serialization format. "BSON" stands for "Binary JSON", but BSON and JSON are serialized very differently. BSON is "JSON-like", because objects are represented as name-value pairs, similar to JSON. Unlike JSON, numeric data types are stored as bytes, not strings. BSON is mainly used as a data storage and network transfer format in the MongoDB database.

According to ASP.Net Web API 2.1 release;

  • The BSON was designed to be lightweight, easy to scan, and fast to encode/decode.
  • BSON is comparable in size to JSON. Depending on the data, a BSON payload may be smaller or larger than a JSON payload. For serializing binary data, such as an image file, BSON is smaller than JSON, because the binary data does is not base64-encoded.
  • BSON documents are easy to scan because elements are prefixed with a length field, so a parser can skip elements without decoding them.
  • Encoding and decoding are efficient, because numeric data types are stored as numbers, not strings.

Native clients, such as .NET client apps, can benefit from using BSON in place of text-based formats such as JSON or XML. For browser clients, you will probably want to stick with JSON, because JavaScript can directly convert the JSON payload.
Advantage of WEB API is, we can have content negotiation. So the client can select in which format does he need the data.

Create ASP.net Web API project. Update ASP.net Web API nuget packages.
In WebApiConfig file add BsonMediaTypeFormatter. Now if the client requests "application/bson", Web API will use BSON formatting as the response.
Add a simple class called Student.
Add a api controller called StudentController and change the Index method like below.
Using fiddle compose a json message like below.
And the response will be like;
Now set the accept header as application/bson.
Now the response will be like;
In general speaking, if your service returns more binary, numeric and non textual data, then BSON is the best thing to use.

No comments:

Post a Comment