Implementing Multiple Serialization Options - ASP.NET Web API 2: Beginner Guide (2015)

ASP.NET Web API 2: Beginner Guide (2015)

Implementing Multiple Serialization Options

Web API supports numerous serialization methods, including XML and JSON. In the sections to follow, we’ll take a closer look at how to implement these three methods and then compare their behavior. Before doing that, however, let’s modify the sample Web API project to return bulk data so we can better understand and compare the performance of the serialization methods. Listing 7 shows how the GetProducts() method updated to return bulk data.

private void GetProducts()


for (int i = 0; i < 5000; i++)


products.Add(new Product { Id = i, Name = "Product - "+i,

Category = "The ASP.NET and Visual Web Developer teams have released the ASP.NET and Web Tools 2012.2 update, which extends the existing ASP.NET runtime and adds new web tooling to Visual Studio 2012. Whether you use Web Forms, MVC, Web API, or any other ASP.NET technology, there is something cool in this update for you.",

Price = 1 });



Listing 7: Updating the GetProducts() method

Using JSON Serialization

Web API uses JSON as its default serialization method. As a result, when you run the Web API project, the results are automatically returned in the JSON format. For example, to retrieve details from Products, you need only use the syntax http://<<server>>:<<port>>/api/Products to return the results in the JSON format.

Using XML Serialization

To use the XML serialization method in a Web API project, you must modify the Global.asax file by inserting the following two lines of code at the end of Application_Start() method:


GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

After implementing the XML serialization method, you can retrieve details from Products by using the syntax http://<<server>>:<<port>>/api/Products, the same syntax used for JSON.