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.
- CREATE TABLE [dbo].[Customer](
- [CustomerId] [int] IDENTITY(1,1) NOT NULL,
- [CustomerName] [nvarchar](50) NULL,
- [PhoneNumber] [nvarchar](50) NULL,
- [Email] [nvarchar](50) NULL,
- [Location] [nvarchar](50) NULL,
- CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
- (
- [CustomerId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- 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
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
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
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.
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.
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click Next.
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.
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.
After clicking on NEXT another window will appear. Choose database table name, as shown in the below screenshot. Then, click on Finish.
Entity Framework will be added and the respective class gets generated under the Models folder.
The following class will be added.
- namespace Customer_Demo.Models
- {
- using System;
- using System.Collections.Generic;
-
- public partial class Customer
- {
- public int CustomerId { get; set; }
- public string CustomerName { get; set; }
- public string PhoneNumber { get; set; }
- public string Email { get; set; }
- public string Location { get; set; }
- }
- }
Step 4
Right click on Controllers folder, select Add, then choose Controller, as shown in the below screenshot.
After clicking on the Controller, a window will appear. Choose Web API 2 Controller-Empty and click on Add.
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.
Complete code for controller
- using Customer_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
- namespace Customer_Demo.Controllers
- {
- public class CustomerController : ApiController
- {
- public IEnumerable<Customer> Get()
- {
- using (DBModel db=new DBModel ())
- {
- return db.Customers.ToList();
- }
- }
- public Customer Get(int id)
- {
- using (DBModel db = new DBModel())
- {
- return db.Customers.FirstOrDefault(c => c.CustomerId == id);
- }
- }
- }
- }
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
Step 6
Now, to change media formatter, we will create custom media formatter WebApiConfig.cs.
Add namespace
- using System.Net.Http.Formatting;
- using System.Net.Http.Headers;
Create custom class
- public class CustomJSONFormatter:JsonMediaTypeFormatter
- {
- public CustomJSONFormatter()
- {
- this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
-
- }
- public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
- {
- base.SetDefaultContentHeaders(type, headers, mediaType);
- headers.ContentType = new MediaTypeHeaderValue("application/json");
- }
- }
Register custom class in config.
- config.Formatters.Add(new CustomJSONFormatter());
Complete WebApiConfig.cs code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Web.Http;
- using Microsoft.Owin.Security.OAuth;
- using Newtonsoft.Json.Serialization;
- using System.Net.Http.Formatting;
- using System.Net.Http.Headers;
-
- namespace Customer_Demo
- {
- public static class WebApiConfig
- {
- public class CustomJSONFormatter:JsonMediaTypeFormatter
- {
- public CustomJSONFormatter()
- {
- this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
-
- }
- public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
- {
- base.SetDefaultContentHeaders(type, headers, mediaType);
- headers.ContentType = new MediaTypeHeaderValue("application/json");
- }
- }
-
- public static void Register(HttpConfiguration config)
- {
-
-
- config.SuppressDefaultHostAuthentication();
- config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
-
-
- config.MapHttpAttributeRoutes();
-
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
-
- config.Formatters.Add(new CustomJSONFormatter());
- }
- }
- }
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.
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.