How To Customize Media Formatter In Web API And Retrieve In XML And JSON Format

Introduction

In this article, I will demonstrate how we can customize ASP.NET Web API Media Formatter and retrieve the data in a format as we want like XML or JSON. I will retrieve data from the SQL database and format them in JSON format. XML is default format in ASP.NET Web API.

Step 1

Open SQL Server 2014 or your choice create a table insert some records.

  1. CREATE TABLE [dbo].[Customer](  
  2.     [CustomerId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [CustomerName] [nvarchar](50) NULL,  
  4.     [PhoneNumber] [nvarchar](50) NULL,  
  5.     [Email] [nvarchar](50) NULL,  
  6.     [Location] [nvarchar](50) NULL,  
  7.  CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [CustomerId] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  11. ) ON [PRIMARY]  
  12.   
  13. GO  

Step 2

Open Visual Studio 2015, click on New Project and create an empty web application project.

Screenshot for creating a new project 1

ASP.NET

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET web application, give a meaningful name to your project, and then click on OK, as shown in below screenshot.

Screenshot for creating a new project 2

ASP.NET

After clicking on OK, one more window will appear; choose Web API, check on MVC and Web API checkbox then click on OK, as shown in the below screenshot.

Screenshot for creating a new project 3

ASP.NET 

After clicking OK, the project will be created with the name of Customer_Demo.

Step 3

Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item and click on it.

ASP.NET 

After clicking on the New item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name DBModels (this name is not mandatory you can give any name) and click on Add.

 ASP.NET

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click Next.

ASP.NET 

After clicking on Next, a window will appear. Choose New Connection. Another window will appear,. Add your server name; if it is local then enter dot (.). Choose your database and click on OK.

ASP.NET 

Connection will be added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config, then click on Next.

 ASP.NET

After clicking on NEXT another window will appear. Choose database table name, as shown in the below screenshot. Then, click on Finish.

ASP.NET 

Entity Framework will be added and the respective class gets generated under the Models folder.

ASP.NET

The following class will be added.

  1. namespace Customer_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Customer  
  7.     {  
  8.         public int CustomerId { get; set; }  
  9.         public string CustomerName { get; set; }  
  10.         public string PhoneNumber { get; set; }  
  11.         public string Email { get; set; }  
  12.         public string Location { get; set; }  
  13.     }  
  14. }  

Step 4

Right click on Controllers folder, select Add, then choose Controller, as shown in the below screenshot.

ASP.NET

After clicking on the Controller, a window will appear. Choose Web API 2 Controller-Empty and click on Add.

ASP.NET 

After clicking on Add, another window will appear with DefaultController. Change the name to CustomerController, then click on Add. CustomerController will be added under Controllers folder. Remember! Don’t change the Controller suffix for all controllers, change only highlights, and instead of Default, just change Home, as shown in the below screenshot.

ASP.NET 

Complete code for controller

  1. using Customer_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8.   
  9. namespace Customer_Demo.Controllers  
  10. {  
  11.     public class CustomerController : ApiController  
  12.     {  
  13.         public IEnumerable<Customer> Get()  
  14.         {  
  15.             using (DBModel db=new DBModel ())  
  16.             {  
  17.                 return db.Customers.ToList();  
  18.             }  
  19.         }  
  20.         public Customer Get(int id)  
  21.         {  
  22.             using (DBModel db = new DBModel())  
  23.             {  
  24.                 return db.Customers.FirstOrDefault(c => c.CustomerId == id);  
  25.             }  
  26.         }  
  27.     }  
  28. }  

Step 5

Build project and run project by pressing ctrl+F5.

  • URL - portnumeber/api/controllerName
  • URL - portnumeber/api/controllerName/id (search customer by id)

Output

 ASP.NET

Step 6

Now, to change media formatter, we will create custom media formatter WebApiConfig.cs.

Add namespace

  1. using System.Net.Http.Formatting;  
  2. using System.Net.Http.Headers;  

Create custom class

  1. public class CustomJSONFormatter:JsonMediaTypeFormatter  
  2.         {  
  3.             public CustomJSONFormatter()  
  4.             {  
  5.                 this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
  6.   
  7.             }  
  8.             public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)  
  9.             {  
  10.                 base.SetDefaultContentHeaders(type, headers, mediaType);  
  11.                 headers.ContentType = new MediaTypeHeaderValue("application/json");  
  12.             }  
  13.         }  

Register custom class in config.

  1. config.Formatters.Add(new CustomJSONFormatter());  

Complete WebApiConfig.cs code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using Microsoft.Owin.Security.OAuth;  
  7. using Newtonsoft.Json.Serialization;  
  8. using System.Net.Http.Formatting;  
  9. using System.Net.Http.Headers;  
  10.   
  11. namespace Customer_Demo  
  12. {  
  13.     public static class WebApiConfig  
  14.     {  
  15.         public class CustomJSONFormatter:JsonMediaTypeFormatter  
  16.         {  
  17.             public CustomJSONFormatter()  
  18.             {  
  19.                 this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
  20.   
  21.             }  
  22.             public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)  
  23.             {  
  24.                 base.SetDefaultContentHeaders(type, headers, mediaType);  
  25.                 headers.ContentType = new MediaTypeHeaderValue("application/json");  
  26.             }  
  27.         }  
  28.   
  29.         public static void Register(HttpConfiguration config)  
  30.         {  
  31.             // Web API configuration and services  
  32.             // Configure Web API to use only bearer token authentication.  
  33.             config.SuppressDefaultHostAuthentication();  
  34.             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));  
  35.   
  36.             // Web API routes  
  37.             config.MapHttpAttributeRoutes();  
  38.   
  39.             config.Routes.MapHttpRoute(  
  40.                 name: "DefaultApi",  
  41.                 routeTemplate: "api/{controller}/{id}",  
  42.                 defaults: new { id = RouteParameter.Optional }  
  43.             );  
  44.   
  45.             config.Formatters.Add(new CustomJSONFormatter());  
  46.         }  
  47.     }  
  48. }  

Step 7

Save and build the solution and run your project by pressing Ctrl+F5.

  • URL - portnumeber/api/controllerName
  • URL - portnumeber/api/controllerName/id (search customer by id)

Output in JSON format.

ASP.NET

Conclusion

I have explained Media Formatter in ASP.NET Web API by creating a custom class and registering the class with config. I hope this will be helpful.