Monday, November 30, 2015

Demystify Web API Versioning

Demystify Web API Versioning

Concert crowd
Since technology is evolving every day, you may have the opportunity to upgrade your existing business needs and this tutorial is about WebApi Versioning using Routing. Once you have published a successful API, the client/consumers will start depending on it, but change is required as business grows. Requirements are being changed every day and here the idea occurred to me to create a new API without tampering with an existing one. There are various ways to do this, like URL, Custom header, Query String and Accept Header.
Web API Versioning using URI:
First, I will cover WebApi versioning using an URL in this section before proceeding. I’d like to share one of the possible situations when you may need this. So let’s dive into it in a practical way.
You might have a situation in which you already have a running WebApi hosted on a server and plenty of end users are getting its benefits. For an example, here the current API is returning a response in JSON format as shown below:
JSON format
Down the line, the customer may desire to have a few more things without messing with the existing one. After considering a new requirement, the client needs a few more fields from the same API to maintain their policies at the business level, so now we can consider a new version of the API with a few more fields like City and Gender in employee in response as depicted below:
response as depicted
To do this we’ll set a new route for the new version of the WebApi Version number in the URI, considering the most common way of versioning so we can consume a resource by callinghttp://localhost:57888/api/v1/Employees/FetchEmployeeById/1 (the client wants to use version 1 of the API) or http://localhost:57888/api/v2/employeesv2/FetchEmployeeById/1 (the client wants to use version 2 of the API).
To implement this we need to add two new routes inside the Register method in the “WebApiConfig” class as in the code below:
code
Notice in the code shown previously there are two new routes and mapped each route with its corresponding controller. In other words, the Route named “Version1? is by default mapped to the controller “Employees? and the Route named “Version2Api” is mapped to the Controller EmployeesV2.
Assume we want to add a new version, V3, of the existing WebApi. Then we need to add a new route to WebApiConfig.cs and so on.
Before proceeding I’d like to share how WebApi selects an appropriate controller from the current request. There is a class DefaultHttpControllerSelector that has the method SelectController, that method has the parameter HttpRequestMessage to maintain the information of route data including controller name defined in the class WebApiConfig. Based on this information it fetches the controller/classes collection using reflection derived from the ApiController base class.
The following is a code snippet for CustomControllerSelector:

  1: public class CustomControllerSelector : DefaultHttpControllerSelector
  2: {
  3:     private HttpConfiguration _config;
  4:     public CustomControllerSelector(HttpConfiguration config)
  5:         : base(config)
  6:     {
  7:         _config = config;
  8:     }
  9: 
 10:     public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
 11:     {
 12:         try
 13:         {
 14:             var controllers = GetControllerMapping();
 15:             var routeData = request.GetRouteData();
 16: 
 17:             var controllerName = routeData.Values["controller"].ToString();
 18: 
 19:             HttpControllerDescriptor controllerDescriptor;
 20: 
 21:             if (controllers.TryGetValue(controllerName, out controllerDescriptor))
 22:             {
 23:                 return controllerDescriptor;
 24:             }
 25:             return null;
 26:         }
 27:         catch (Exception ex)
 28:         {
 29:             throw ex;
 30:         }
 31: 
 32:     }
 33: }
 34: 
Add “CustomControllerSelector” to WebApiConfig.cs to get its benefit as shown below:

  1. config.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector((config))); 

Code snippet for Version v1
Kindly find the code below for the EmployeesController class and Employee Model class that represent version v1 of the WebApi as shown below:

  1: public class EmployeesController : ApiController
  2: {
  3:     public static IList<Employee> listEmp = new List<Employee>()  
  4:     {  
  5:         new Employee()  
  6:                 {  
  7:                     ID =001, FirstName="Sachin", LastName="Kalia"
  8:                 },  
  9:         new Employee()  
 10:                 {  
 11:                     ID =002, FirstName="Dhnanjay" ,LastName="Kumar"
 12:                 },  
 13:         new Employee()  
 14:                 {  
 15:                     ID =003, FirstName="Ravish", LastName="Sindhwani"
 16:                 },  
 17:         new Employee()  
 18:                 {  
 19:                     ID =004, FirstName="Rahul" ,LastName="Saxena"
 20:                 },  
 21:     };
 22: 
 23:     [AcceptVerbs("GET")]
 24:     public Employee FetchEmployeeById(int id)
 25:     {
 26:         return listEmp.First(e => e.ID == id);
 27:     }
 28: }
 29: 
 30: public class Employee
 31: {
 32:     public int ID { get; set; }
 33:     public string FirstName { get; set; }
 34:     public string LastName { get; set; }
 35: 
 36: }
 37: 
To test this please press F5 and run you WebApi.
WebApi
To test this we need to issue a GET request using the Web Proxy tool Fiddler as in the image below. Kindly copy and paste the following URL that specifies version v1:
http://localhost:57888/api/v1/Employees/FetchEmployeeById/1
GET request using Web Proxy tool
Code snippet for Version v2
Kindly find the code below for the EmployeesV2Controller class and EmployeeV2 Model class that specifies version v2 of the WebApi:
      1: public class EmployeesV2Controller : ApiController
      2: {
      3:     public static IList<EmployeeV2> listEmp = new List<EmployeeV2>()  
      4:     {  
      5:         new EmployeeV2()  
      6:                 {  
      7:                     ID =001, FirstName="Sachin", LastName="Kalia",City="Noida",Gender="Male"
      8:                 },  
      9:         new EmployeeV2()  
     10:                 {  
     11:                     ID =002, FirstName="Dhnanjay" ,LastName="Kumar", City="Gurgaon",Gender="Male"
     12:                 },  
     13:         new EmployeeV2()  
     14:                 {  
     15:                     ID =003, FirstName="Ravish", LastName="Sindhwani", City="indianapolis",Gender="Male"
     16:                 },  
     17:         new EmployeeV2()  
     18:                 {  
     19:                     ID =004, FirstName="Neeraj", LastName="Arora", City="San Francisco",Gender="Male"
     20:                 },  
     21:         new EmployeeV2()  
     22:                 {  
     23:                     ID =005, FirstName="Rahul" ,LastName="Saxena", City="Hydrabad",Gender="Male"
     24:                 },  
     25:         new EmployeeV2()  
     26:                 {  
     27:                     ID =006, FirstName="Anshu" ,LastName="Agarwal", City="Noida",Gender="Female"
     28:                 },  
     29: 
     30:     };
     31: 
     32:     [AcceptVerbs("GET")]
     33:     public EmployeeV2 FetchEmployeeById(int id)
     34:     {
     35:         var coll = listEmp.FirstOrDefault(e => e.ID == id);
     36:         return coll;
     37:     }
     38: }
     39: 
     40: public class EmployeeV2
     41: {
     42:     public int ID { get; set; }
     43:     public string FirstName { get; set; }
     44:     public string LastName { get; set; }
     45:     public string City { get; set; }
     46:     public string Gender { get; set; }
     47: }

Press F5 and run you WebApi.
To test this we need to issue a GET request using the Web Proxy tool Fiddler as in the image below. Kindly copy and paste the following URL that specifies version v2 into the Web Proxy tool Fiddler:
http://localhost:57888/api/v2/employeesv2/FetchEmployeeById/1.
Web Proxy tool
Web API Versioning using QueryString parameter
WebApi versioning with query string parameter is a simple way to this, because everything is dependent on the query string parameter only.
We’ll specify the defined version of the WebApi in the request parameter. Using that parameter the SelectController class will identify which controller I need to call in order to respond to the client.
Added a new method into the existing CustomControllerSelector and made small amendments in the SelectController class as shown below in a code snippet.
      1: public override HttpControllerDescriptor SelectController(HttpRequestMessage request)  
      2: {  
      3:     try  
      4:     {  
      5:         var controllers = GetControllerMapping();  
      6:         var routeData = request.GetRouteData();  
      7:   
      8:         var controllerName = routeData.Values["controller"].ToString();  
      9:         HttpControllerDescriptor controllerDescriptor;  
     10:   
     11:         string versionNum= GetVersionFromQueryString(request);  
     12:   
     13:         if (versionNum == "v1")  
     14:         {  
     15:             if (controllers.TryGetValue(controllerName, out controllerDescriptor))  
     16:             {  
     17:                 return controllerDescriptor;  
     18:             }  
     19:         }  
     20:         else   
     21:         {  
     22:             controllerName= string.Concat(controllerName,"V2");  
     23:             if (controllers.TryGetValue(controllerName, out controllerDescriptor))  
     24:             {  
     25:                 return controllerDescriptor;  
     26:             }  
     27:         }  
     28:   
     29:         return null;  
     30:     }  
     31:     catch (Exception ex)  
     32:     {  
     33:         throw ex;  
     34:     }  
     35: }  
     36:   
     37: /// <summary>  
     38: /// Method to Get Query String Values from URL to get the version number  
     39: /// </summary>  
     40: /// <param name="request">HttpRequestMessage: Current Request made through Browser or Fiddler</param>  
     41: /// <returns>Version Number</returns>  
     42:   
     43: private string GetVersionFromQueryString(HttpRequestMessage request)  
     44: {  
     45:     var versionStr = HttpUtility.ParseQueryString(request.RequestUri.Query);  
     46:   
     47:     if (versionStr[0] != null)  
     48:     {  
     49:         return versionStr[0];  
     50:     }  
     51:     return "V1";  
     52: }  

Press F5 and run you WebApi.
Kindly paste the following URL into Fiddler to verify the working behavior.
http://localhost:57888/api/employees/FetchEmployeeById/2?V2
Kindly have a look at the image shown below:
response from WebApi with version
In the same way you can try with:
http://localhost:57888/api/employees/FetchEmployeeById/1?V1
json
Web API Versioning using Custom Header parameter
So far we’ve seen WebApi with the two techniques URL and Query String. The next WebApi versioning techniques with CustomHeader parameter is an easy way to do versioning. For this example we’ve used customHeader Name “Version-Num” that we must send into the current request.
We’ll specify the desired version of the WebApi in the CustomHeader request. Using that parameter the SelectController class will identify the controller I need to call in order to respond to the client.
Added a new method into the existing CustomControllerSelector and made small amendments in the SelectController class as shown below in a code snippet.

  1: /// <summary>  
  2: /// Method to Get Header Values.  
  3: /// </summary>  
  4: /// <param name="request">HttpRequestMessage: Current Request made through        Browser or Fiddler  
  5: </param>  
  6: /// <returns>Version Number</returns>  
  7: private string GetVersionFromHeader(HttpRequestMessage request)  
  8: {  
  9:     const string HEADER_NAME = "Version-Num";  
 10:   
 11:     if (request.Headers.Contains(HEADER_NAME))  
 12:     {  
 13:         var versionHeader = request.Headers.GetValues(HEADER_NAME).FirstOrDefault();  
 14:         if (versionHeader != null)  
 15:         {  
 16:             return versionHeader;  
 17:         }  
 18:     }  
 19:   
 20:     return "V1";  
 21: } 
To test this we need to issue a GET request using Fiddler as in the image below, note how we added the new header “Version-Num” to the request header collection.
Web API Versioning using Accept Header parameterSo far we’ve seen WebApi with the three techniques URL, Query String and CustomHeader.
The next WebApi versioning technique uses an AcceptHeader parameter that is an easy way to do WebApi versioning. For this example we’ve used an Accept Header value Accept: application/json or "Accept: application/xml, that we need to send into the current request.
For this approach we’ve added a new method in the existing CustomControllerSelector and made small amendments in the SelectController class as shown below in a code snippet.

  1: /// <summary>  
  2: /// Method to Get Accept Header Values.  
  3: /// </summary>  
  4: /// <param name="request">HttpRequestMessage: Current Request made through Browser or Fiddler</param>  
  5: /// <returns>Version Number</returns>  
  6: private string GetVersionFromAcceptHeader(HttpRequestMessage request)  
  7: {  
  8:     var acceptHeader = request.Headers.Accept;  
  9:   
 10:     foreach (var mime in acceptHeader)  
 11:     {  
 12:         if (mime.MediaType == "application/json")  
 13:         {                      
 14:             return "V2";  
 15:         }  
 16:         else if (mime.MediaType == "application/xml")  
 17:         {  
 18:             return "V1";  
 19:         }  
 20:         else { return "V1"; }  
 21:   
 22:     }  
 23:     return "V1";  
 24: }  
Note: We are assuming that if the end-user/client doesn’t provide a value then we will consider it to be Version V1. Kindly have a look at the image shown below:
consider the Version V1
Now if we replace Accept: application/xml with application/json then it should respond from WebApi version V2. Kindly have a look at the image shown below:
response from WebApi
You can also get more details about the Media Types formatter using the link shown below: 
Note: It might be one of the questions in an interview.

Download source code from here : Demystify Web API Versioning- Source Code







Sunday, November 22, 2015

Bind DropDownListFor at runtime in MVC : An Essential Tip

During an implementation of MVC View page ,I struggled little to bind the DropDownList with the runtime value from ViewModel . Here is the pictorial representation to Bind the DropDownList at runtime.

Image Representation As depicted below:

Hope it will help you to bind DropDownListFor at runtime.

To know more MVC and WebApi Kindly go through with these links

MVC Articles & WCF and WebAPI

Thanks.
Enjoy coding and reading.

Thursday, November 19, 2015

Custom Directive in AngularJS

Custom Directive in AngularJS : A Simplified practical approach
Concert crowd
This tutorial is about to create Custom Directives in Angular JS I feel it would be a good brain teaser if I come with some real time example. Generally we use directives in AngularJS and this is how Directives makes AngularJS so powerful. Directives are the key part of AngularJS and I belied every person works upon angular should know its benefits.
AngularJS is bundled with powerful directives out of the box In this post, we’ll focus on how to create your own custom directives which may be one of your project needs. Though Example is simple but idea is to understand the depth.
An excerpt from docs.angularjs.org as given below about directives is :
At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.
Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngClass. Much like you create controllers and services, you can create your own directives for Angular to use.
If you have used Angular anymore certainly you have confronted with keyword ng-. This is what we will discuss and create.
This is one of the already built in directive as shown below in short code snippet start with ng-model:
       1:  <input type="text" ng-model="firstName"><br/>  


Directive types
All of the Angular-provided directives match attribute name, tag name, comments, or class name. The following demonstrates the various ways a directive (myDir in this case) can be referenced from within a template:
As an element:
  1: As an element:  
  2: <custom-Dir></custom-Dir>  
  3: As an attribute:  
  4: <span custom-Dir ></span>  
  5: As an attribute:  
  6: <span class=" custom-Dir: exp;"></span>  
  7: As a comment:  
  8: <!-- directive: custom-Dir exp -->  
  9: 


  1. Custom Directive Syntax: 
  1: app.directive("customDir", function () {  
  2: return {  
  3:         restrict: "E",        // directive is an Element (not Attribute)
  4:         scope: {              // set up directive's isolated scope
  5:             name: "@",          // name var passed by value (string, one-way)
  6:             amount: "=",        // amount var passed by reference (two-way)
  7:             save: "&" // save action
  8:         },  
  9:         template:             // replacement HTML (can use our scope vars here)
 10: "<div></div>",  
 11:         replace: true,        // replace original markup with template
 12:         transclude: false,    // do not copy original HTML content
 13:         controller: [ "$scope", function ($scope) {   }],  
 14:         link: function (scope, element, attrs, controller) { //define function, used for DOM manipulation }
 15:     }  
 16: });  
 17: 

The actual code implementation of the custom directive is shown below:
      1: app.directive("customDir", function () {  
      2: return {  
      3:         restrict: "EA",  
      4:         scope: false,  
      5:         template: "<div>Your name is : {{firstName}} + {{lastName}}</div>" +  
      6: "Change your name : <input type='text' ng-model='firstName' />",  
      7:         replace: false
      8: 
      9:     };  
     10: }); 

Or

  1: app.directive("customDir", function () {  
  2: return {  
  3:         restrict: "EA",  
  4:         scope: false,  
  5:         template: "<div>Your name is : {{firstName}} + {{lastName}}</div>" +  
  6: "<b>Change your first name : </b> <input type='text' ng-model='firstName' />",  
  7:         replace: false,  
  8:         link: function ($scope, element, attrs) {  
  9:             element.on('click', function () {  
 10:                 $scope.firstName = "Clicked on Custom Directive !!!";  
 11:             });  
 12:         }  
 13: 
 14:     };  
 15: });  
 16: 


In this example I’ve created element and attribute directive and restricted as EA. Scope means it will use the parents scope . 3rd is template which is utilizing the controller scope value as default. Hope you are familiar with scope variable .In 4th point I’ve added click event on this directive and updating the scope’s first name value. As soon as you click on this directive it updates the value of first name scope variable.
If I run an application it shows the following screen as depicted below:

If I inspect an element than I can easily see that it has added into DOM as showing below in screen shot:



Now if I change in text box value it works perfectly and update the value of first name where ever it is bind on html page.





Hope it will help you somewhere and thanks for reading this.

To know more MVC and WebApi Kindly go through with these links
MVC Articles & WCF and WebApi
Thanks.
Enjoy coding and reading








Thursday, October 8, 2015

Log4net.dll to Log Information

Log4net.dll to Log Information

Hi Geeks
My new article states how to use the Log4net's external Log4net.dll to log information that might be beneficial for error tracking and other tracing issues.
There are a few things that you need to consider during the implementation. I've also attached the code segment to understand the code better and in a more convenient way for all geeks, who want to implement log4net in their project or for specific their requirements.
You can download the desired Log4net.dll from this path: http://logging.apache.org/log4net/download.html,
Whilst I've also attached the required Log4net.dll in Solution.
Log4net is an open source project based on the work of many authors. It allows the developer to control what log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files. This is how the solution looks after adding this DLL:
image1.png
We also need to configure the external configuration file; this file is like the root of any application that keeps the information of appenders, filters, config section and much more.
In order to embed the configuration data in the .config file the section name must be identified to the .NET config file parser using a configSections element. The section must specify the "log4net.Config.Log4NetConfigurationSectionHandler" that parses the config section. This type must be fully assembly qualified because it is being loaded by the .NET config file parser, not by log4net.
The correct assembly name for the log4net assembly must be specified. The following is a simple example configuration file that specifies the correct section handler to use for the log4net section. Kindly refer to this link for more in-depth information about this section.http://logging.apache.org/log4net/release/manual/configuration.html
There are two appenders I've used in this sample application named LogFileAppender and SmtpAppender as described below:
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >for logging information using Log4net object, e.g. log.Debug, log.InfoFormat along with other methods.
image2.png
SmtpAppender, as shown in the tag <appender name="EmailAppender"type="log4net.Appender.SmtpAppender"> sends mail to an on-demand person or group.
image5.jpg
image6.jpg
Kindly have a look at the app.config file at least once that plays an important role here and also keeps secure information like under SmtpAppender to send mail to the destination.
image4.png
To send an email to the desired address you must explore the log.Warn and log.FatalFormat methods.
I've attached the sample application as an attachment. Enjoy coding.
See you soon with more articles.
Thanks, Sachin Kalia

Wednesday, October 7, 2015

Modify the value of readonly varibale

Modify the value of readonly varibale

Concert crowd

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

This is how we declare a readonly variable:

  1: public readonly int objreadonly = 100;

You can only change the value of a readonly variable at the constructor level of the same class.

An Excerpt about readonly is :

A readonly field can only be set upon field initialization or in a constructor. This gives considerable benefit for ongoing maintenance because you can ensure it was set when the object was created and not modified since. Though there is no performance benefit.

I have used a little practical demonstarion of this.

  1: class Readonly
  2: 
  3:     {
  4: public readonly int objreadonly = 100;
  5:         Readonly()
  6:         {
  7:         }
  8: public void  ChangeValueofReadonly()
  9:         {
 10:             objreadonly = 200;
 11:         }
 12:     }
 13: class Program
 14:     {
 15: static void Main(string[] args)
 16:         {
 17:         }
 18:     }
 19: 
 20: 
If you notice I tried to change the value of readonly object "objreadonly" but I'm not successful at changing its value, it issues the error "A readonly field cannot be assigned to (except in a constructor or a variable initializer)" also depicted below in the snap shot.

Readonly-variable-in-Csharp.jpg

In other words you can't change its value at method level at class level. It can change at constructor level only.

Let's do it :

Readonly-variable.jpg

This is a small demonstration that I hope will help you somewhere down the line

Wednesday, August 26, 2015

WebApi: Custom MediaTypeMappings in WebApi MVC 4

WebApi: Custom MediaTypeMappings in WebApi MVC 4

In this article I’ll explain about Custom MediaTypeMappings in WebApi.

Concert crowd

webApi

In this article I'll explain Custom MediaTypeMappings in the WebApi.
From the ASP.NET Web API perspective, serialization is the process of translating a .NET Common Language Runtime (CLR) type into a format that can be transmitted over HTTP. The default format is either JSON or XML
A media type formatter, which is an object of type MediaTypeFormatter, performs the serialization in the ASP.NET Web API pipeline. Consider a simple action method handling GET in an ApiController:
Employee Class Code
By default the ASP.NET Web API framework supports two media or content types: JSON and XML.If you send a request with Accept: application/json then the response message will be JSON and Content-Type will be application/json. Similarly, if you send a request with Accept: application/xml, the response message will be XML. You can also specify a quality value indicating the relative preference. The range is 0–1, with 0 being unacceptable and 1 being the most preferred. The default value is 1. For example, if you send the request header Accept: application/json; q=0.8, application/xml;q=0.9 then the response message will be XML, because application/xml has a quality value of 0.9, that is higher than the quality value of 0.8 specified for application/json.
Kindly can also visit this series of articles to learn about the WebApi:

MediaType Mapping
There is one more way by which the Conneg algorithm decides about the Response's media type and formatter. It is called MediaTypeMapping. Every MediaTypeFormatter has a collection of these mappings in it.

MediaTypeMapping provides a way for the user to add some custom logic and decide whether they would want the formatter to take part in writing the Response. This is different from the default way of just matching media type values (like “application/xml”, “application/xml”) present on the Accept and Request Content-Type headers and making decisions.

Start
Let's create a sample application and do this step-by-step.
Step 1: Let's first create a sample web application using an ASP.NET MVC 4 Web Application and name it as you choose; I used WebApiDemo as shown in the image below:
Create MVC 4 App
Step 2: Click OK and choose the Web API option from the templates shown in the wizard window.
Web API Project Template
Step 3: You'll find the application structure as shown below at first sight.
Application Structure
Step 4: Right-click the Controllers folder in the Solution Explorer of Visual Studio. Select "Add" ➤"Controller" and provide a name of EmployeesController for the controller. Leave the option Empty API Controller selected in the Template dropdown and click "Add", as shown in the figure below. Notice that the generated controller class inherits from ApiController, a class that is part of the ASP.NET Web API framework. Kinldy add the following code into the EmployeesController class.

 

  1: public static IList<Employee> listEmp = new List<Employee>()
  2:         {
  3:             new Employee()
  4:                 {
  5:                     ID =001, FirstName="Sachin", LastName="Kalia",Department="Engineering"
  6:                 },
  7:                 new Employee()
  8:                 {
  9:                     ID =002, FirstName="Dhnanjay" ,LastName="Kumar",Department="Engineering"
 10:                 },
 11:                 new Employee()
 12:                 {
 13:                     ID =003, FirstName="Ravish", LastName="Sindhwani", Department="Finance"
 14:                 },
 15:                 new Employee()
 16:                 {
 17:                     ID =004, FirstName="Amit" ,LastName="Chaudhary",Department="Architect"
 18:                 },
 19:                 new Employee()
 20:                 {
 21:                     ID =004, FirstName="Anshu" ,LastName="Aggarwal",Department="HR"
 22:                 },
 23:         };
Adding Controller

Step 5: Right-click the Models folder in the Solution Explorer of Visual Studio. Select "Add" -> "Class"
to add a new class with a name of Employee.
Adding Class
After creating the Employee class, kindly add the following code into this class.

Employee Class
Now I've added a class CustomMediaTypeMapping that checks if the Request has an “AcceptLanguage” Header called “en-FR”. If it finds the header, then it would inform the Conneg algorithm that it's a full match and that the media type formatter having this MediaTypeMapping is ready to write the response.

Class Code
Note: If you notice, we've overridden TryMatchMediaType that takes HttpRequestMessage and returns “The quality of the match. It must be between 0.0 and 1.0. A value of 0.0 signifies no match. A value of 1.0 signifies a complete match”.

Thinking
Now the question arises, which MediaTypeFormatter will respond to such a MediaTypeMapping. The answer is, add the line given below to the WebApiConfig.cs file placed in the App_Start folder.

Config
It means that whenever a request has Accept-Language: en-FR, JsonFormatter will respond to such a request to the client.

Press F5 and run your application; it will show the following image:

MVC 4 Home Page
Great; the WebApi is up and running.
Now I paste the following URL http://localhost:57888/api/employees/1 into Fiddler and press execute. It responded in application/xml because it has a quality factor of 0.9 that is more than others in the Accept header field as depicted in the following image.
Inspectors

Now I make a slight change to the URL request. Paste the following URL into Fiddler with the same Accept header though this time I have changed the Accept-Language to “en-FR”. Kindly have a look at the image given below:
Parsed
This time we expect the result in application/json format. Press the execute button.
Output
Headers

It responds with a CustomMediaTypeMapping that we've registered in JsonFormatter in WebApiConfig.

Like
Conclusion
In this article we looked into CustomMediaTypeMapping of the WebApi and a way to register with MediaTypeFormatter. I hope you enjoyed this demonstration.

I hope it will help you somewhere down the line. Keep coding and Smile.
Thanks
Sachin Kalia