Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Web API - Get Started
  • What is Web API?
  • Create Web API Project
  • Test Web API
  • Web API Controller
  • Configure Web API
  • Web API Routing
  • Parameter Binding
  • Action Return Type
  • Data Formats
  • Media Type Formatters
  • Web API Filters
  • Create Web API for CRUD
  • Implement Get Method
  • Implement Post Method
  • Implement Put Method
  • Implement Delete Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

ASP.NET Web API: Media-Type Formatters

As you have seen in the previous section that Web API handles JSON and XML formats based on Accept and Content-Type headers. But, how does it handle these different formats? The answer is: By using Media-Type formatters.

Media type formatters are classes responsible for serializing request/response data so that Web API can understand the request data format and send data in the format which client expects.

Web API includes following built-in media type formatters.

Media Type Formatter ClassMIME TypeDescription
JsonMediaTypeFormatterapplication/json, text/jsonHandles JSON format
XmlMediaTypeFormatterapplication/xml, text/jsonHandles XML format
FormUrlEncodedMediaTypeFormatterapplication/x-www-form-urlencodedHandles HTML form URL-encoded data
JQueryMvcFormUrlEncodedFormatterapplication/x-www-form-urlencodedHandles model-bound HTML form URL-encoded data

Retrieve Built-in Media Type Formatters

As mentioned Web API includes above listed media type formatter classes by default. However, you can also add, remove or change the order of formatters.

The following example demonstrates HTTP Get method that returns all built-in formatter classes.

Example: Retrieve Built-in Formatters in C#
public class FormattersController : ApiController
{
    public IEnumerable<string> Get()
    {
        IList<string> formatters = new List<string>();

        foreach (var item in GlobalConfiguration.Configuration.Formatters)
        {
            formatters.Add(item.ToString());
        }

        return formatters.AsEnumerable<string>();
    }
}

In the above example, GlobalConfiguration.Configuration.Formatters returns MediaTypeFormatterCollection that includes all the formatter classes. The above example returns names of all the formatter classes as shown below.

Built-in Media-Type Formatters

Alternatively, MediaTypeFormatterCollection class defines convenience properties that provide direct access to three of the four built-in media type formatters. The following example demonstrates retrieving media type formatters using MediaTypeFormatterCollection's properties.

Example: Retrieve Built-in Formatters in C#
public class FormattersController : ApiController
{
    public IEnumerable<string> Get()
    {
        IList<string> formatters = new List<string>();

        formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter.GetType().FullName);
        formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter.GetType().FullName);
        formatters.Add(GlobalConfiguration.Configuration.Formatters.FormUrlEncodedFormatter.GetType().FullName);
        
        return formatters.AsEnumerable<string>();
    }
}

The above example returns following response to the browser.

Media-Type Formatters

BSON Formatter

Web API also supports BSON format. As the name suggests, BSON is binary JSON, it is a binary-encoded serialization of JSON-like documents. Currently there is very little support for BSON and no JavaScript implementation is available for clients running in browsers. This means that it is not possible to retrieve and automatically parse BSON data to JavaScript objects.

Web API includes built-in formatter class BsonMediaTypeFormatter for BSON but it is disabled by default. Learn more about BSON support in Web API here.

JSON Formatter

As mentioned above, Web API includes JsonMediaTypeFormatter class that handles JSON format. The JsonMediaTypeFormatter converts JSON data in an HTTP request into CLR objects (object in C# or VB.NET) and also converts CLR objects into JSON format that is embeded within HTTP response.

Internally, JsonMediaTypeFormatter uses third-party open source library called Json.NET to perform serialization.

Configure JSON Serialization

JSON formatter can be configured in WebApiConfig class. The JsonMediaTypeFormatter class includes various properties and methods using which you can customize JSON serialization. For example, Web API writes JSON property names with PascalCase by default. To write JSON property names with camelCase, set the CamelCasePropertyNamesContractResolver on the serializer settings as shown below.

Example: Customize JSON Serialization in C#
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
            
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // configure json formatter
        JsonMediaTypeFormatter jsonFormatter = config.Formatters.JsonFormatter;

        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

XML Formatter

The XmlMediaTypeFormatter class is responsible for serializing model objects into XML data. It uses System.Runtime.DataContractSerializer class to generate XML data.

Learn more about configuring JSON and XML serialization here.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.