"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Media Formatters in ASP.NET Web API 2

by Mike Wasson

This tutorial shows how support additional media formats in ASP.NET Web API.

Internet Media Types

A media type, also called a MIME type, identifies the format of a piece of data. In HTTP, media types describe the format of the message body. A media type consists of two strings, a type and a subtype. For example:

When an HTTP message contains an entity-body, the Content-Type header specifies the format of the message body. This tells the receiver how to parse the contents of the message body.

For example, if an HTTP response contains a PNG image, the response might have the following headers.

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Content-Length: 95267
   3:  Content-Type: image/png

When the client sends a request message, it can include an Accept header. The Accept header tells the server which media type(s) the client wants from the server. For example:

[!code-consoleMain]

   1:  Accept: text/html,application/xhtml+xml,application/xml

This header tells the server that the client wants either HTML, XHTML, or XML.

The media type determines how Web API serializes and deserializes the HTTP message body. Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.

To create a media formatter, derive from one of these classes:

Deriving from BufferedMediaTypeFormatter is simpler, because there is no asynchronous code, but it also means the calling thread can block during I/O.

Example: Creating a CSV Media Formatter

The following example shows a media type formatter that can serialize a Product object to a comma-separated values (CSV) format. This example uses the Product type defined in the tutorial Creating a Web API that Supports CRUD Operations. Here is the definition of the Product object:

[!code-csharpMain]

   1:  namespace ProductStore.Models
   2:  {
   3:      public class Product
   4:      {
   5:          public int Id { get; set; }
   6:          public string Name { get; set; }
   7:          public string Category { get; set; }
   8:          public decimal Price { get; set; }
   9:      }
  10:  }

To implement a CSV formatter, define a class that derives from BufferedMediaTypeFormater:

[!code-csharpMain]

   1:  namespace ProductStore.Formatters
   2:  using System;
   3:  using System.Collections.Generic;
   4:  using System.IO;
   5:  using System.Net.Http;
   6:  using System.Net.Http.Formatting;
   7:  using System.Net.Http.Headers;
   8:  using ProductStore.Models;
   9:   
  10:  namespace ProductStore.Formatters
  11:  {
  12:      public class ProductCsvFormatter : BufferedMediaTypeFormatter
  13:      {
  14:      }
  15:  }

In the constructor, add the media types that the formatter supports. In this example, the formatter supports a single media type, “text/csv”:

[!code-csharpMain]

   1:  public ProductCsvFormatter()
   2:  {
   3:      // Add the supported media type.
   4:      SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
   5:  }

Override the CanWriteType method to indicate which types the formatter can serialize:

[!code-csharpMain]

   1:  public override bool CanWriteType(System.Type type)
   2:  {
   3:      if (type == typeof(Product))
   4:      {
   5:          return true;
   6:      }
   7:      else
   8:      {
   9:          Type enumerableType = typeof(IEnumerable<Product>);
  10:          return enumerableType.IsAssignableFrom(type);
  11:      }
  12:  }

In this example, the formatter can serialize single Product objects as well as collections of Product objects.

Similarly, override the CanReadType method to indicate which types the formatter can deserialize. In this example, the formatter does not support deserialization, so the method simply returns false.

[!code-csharpMain]

   1:  public override bool CanReadType(Type type)
   2:  {
   3:      return false;
   4:  }

Finally, override the WriteToStream method. This method serializes a type by writing it to a stream. If your formatter supports deserialization, also override the ReadFromStream method.

[!code-csharpMain]

   1:  public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
   2:  {
   3:      using (var writer = new StreamWriter(writeStream))
   4:      {
   5:          var products = value as IEnumerable<Product>;
   6:          if (products != null)
   7:          {
   8:              foreach (var product in products)
   9:              {
  10:                  WriteItem(product, writer);
  11:              }
  12:          }
  13:          else
  14:          {
  15:              var singleProduct = value as Product;
  16:              if (singleProduct == null)
  17:              {
  18:                  throw new InvalidOperationException("Cannot serialize type");
  19:              }
  20:              WriteItem(singleProduct, writer);
  21:          }
  22:      }
  23:  }
  24:   
  25:  // Helper methods for serializing Products to CSV format. 
  26:  private void WriteItem(Product product, StreamWriter writer)
  27:  {
  28:      writer.WriteLine("{0},{1},{2},{3}", Escape(product.Id),
  29:          Escape(product.Name), Escape(product.Category), Escape(product.Price));
  30:  }
  31:   
  32:  static char[] _specialChars = new char[] { ',', '\n', '\r', '"' };
  33:   
  34:  private string Escape(object o)
  35:  {
  36:      if (o == null)
  37:      {
  38:          return "";
  39:      }
  40:      string field = o.ToString();
  41:      if (field.IndexOfAny(_specialChars) != -1)
  42:      {
  43:          // Delimit the entire field with quotes and replace embedded quotes with "".
  44:          return String.Format("\"{0}\"", field.Replace("\"", "\"\""));
  45:      }
  46:      else return field;
  47:  }

Adding a Media Formatter to the Web API Pipeline

To add a media type formatter to the Web API pipeline, use the Formatters property on the HttpConfiguration object.

[!code-csharpMain]

   1:  public static void ConfigureApis(HttpConfiguration config)
   2:  {
   3:      config.Formatters.Add(new ProductCsvFormatter()); 
   4:  }

Character Encodings

Optionally, a media formatter can support multiple character encodings, such as UTF-8 or ISO 8859-1.

In the constructor, add one or more System.Text.Encoding types to the SupportedEncodings collection. Put the default encoding first.

[!code-csharpMain]

   1:  public ProductCsvFormatter()
   2:  {
   3:      SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
   4:   
   5:      // New code:
   6:      SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
   7:      SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"));
   8:  }

In the WriteToStream and ReadFromStream methods, call MediaTypeFormatter.SelectCharacterEncoding to select the preferred character encoding. This method matches the request headers against the list of supported encodings. Use the returned Encoding when you read or write from the stream:

[!code-csharpMain]

   1:  public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
   2:  {
   3:      Encoding effectiveEncoding = SelectCharacterEncoding(content.Headers);
   4:   
   5:      using (var writer = new StreamWriter(writeStream, effectiveEncoding))
   6:      {
   7:          // Write the object (code not shown)
   8:      }
   9:  }



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/formats-and-model-binding/media-formatters.htm
< THANKS ME>