Media Formatters in ASP.NET Web API

Introduction

In this article we will define the Media Type Formatters used in ASP.NET Web API.

What  is the Media Type

Media Type is called the Internet Media Type and also called Multipurpose Internet Mail Extensions (MIME). Media Type determines the format of the data. For HTTP the Media Type sets the format of the message body. The Media Type holds two strings that are as follows:

  1. text/html
  2. application/json

Media Type Formatter in Web API

The Media Type Formatter in the Web API defines how the message body is serialized and desterilized. How to serialize the HTTP message and how to desterilize the HTTP message. It supports the XML and JSON formatters.

If you want to create the media formatter then we need to use the following classes:

  • MediaTypeFormatter: This class is a collection of asynchronous methods. These methods are used for both read and write.
  • BufferedMediaTypeFormatter: This class wraps all the asynchronous methods in synchronous methods.

Creation of Media Type formatter

Now we explain how to create the Media Type formatter. In this example there is an object that is serialized by the media formatter:

namespace webapp

{

    public class Material

    {

        public int id { get; set; }

        public string Mname { get; set; }

        public decimal cost { get; set; }

        public string Type { get; set; }

    }

}

Now we define the class that is derived from the BufferedMediaType Formatter:

namespace webapp.Formatters

{

    using System;

    using System.Collections.Generic;

    using System.IO;

    using System.Net.Http.Formatting;

    using System.Net.Http.Headers;

    using webapp.Models;

 

    public class Material_Format : BufferedMediaTypeFormatter

    {

    }

}

Now we add a constructor in which we add the supported Media Type:

public Material_Format()

{

    SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

}

 

Now we override the method CanWriteType:

 

public override bool CanWriteType(System.Type tp)

{

    if (tp == typeof(Matirial))

    {

        return true;

    }

    else

    {

        Type enum = typeof(IEnumerable<Material>);

        return enum.IsAssignableFrom(tp);

    }

}

 

At last we override the WriteToStream method:

 

public override void WriteToStream(Type tp, object obj, Stream stm, HttpContentHeaders cont)

{

    using (var wrt = new StreamWriter(stm))

    {

 

        var materials = value as IEnumerable<Material>;

        if (material != null)

        {

            foreach (var material in materials)

            {

                WriteItem(material, wrt);

            }

        }

        else

        {

            var onematerial= value as Material;

            if (onematerial == null)

            {

                throw new InvalidOperationException("it can not be serialized");

            }

            WriteItem(onematerial, wrt);

        }

    }

    stm.Close();

}

 
private
void WriteItem(Material material, StreamWriter wrt)

{

    wrt.WriteLine("{0},{1},{2},{3}", Escape(material.Id),

        Escape(material.Name), Escape(material.Category), Escape(material.Price));

}

 

static char[] space = new char[] { ',', '\n', '\r', '"' };

 

private string Escape(object obj1)

{

    if (obj1 == null)

    {

        return "";

    }

    string value = obj1.ToString();

    if (value.IndexOfAny(space) != -1)

    {

        return String.Format("\"{0}\"", value.Replace("\"", "\"\""));

    }

    else

   return value;

} 

 

Adding the Media formatter


 Here we create the object of HttpConfiguration for adding the formatter:

public static void config(HttpConfiguration cn )

{

    cn.Formatters.Add(new Material_Format());

}

 

Now we add this method into the Global.asax file in the Application_Start method for performing the hosting.

 

void Application_Start(object sender, EventArgs e)

        {

           

            protected void Application_Start()

{

    config(GlobalConfiguration.Configuration);

 

}

 

 

After specifying the "text/html/ in the accept header then the server returns the response in HTML format.

HttpClient htp = new HttpClient();

htp.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

 string final = htp.GetStringAsync("localhost:35692/api/materials/").final;

System.IO.File.WriteAllText("materials.html", final);

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all