"ASP. NET Web API Tutorial" 6.1 Media Formatter

Source: Internet
Author: User
Tags hosting

Http://www.cnblogs.com/r01cn/archive/2013/05/17/3083400.html

6.1 Media formatters
6.1 Media Formatter

This article quoted: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

by Mike wasson| March 8, 2012
Mike wasson| Date: 2012-3-8

This tutorial shows how support additional media formats in ASP.
This tutorial demonstrates how to support additional media formats in the ASP.

6.1.1 Internet Media Types
6.1.1 media types for the Internet

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 strings, a type and a subtype. For example:
The media type, also called the MIME type, identifies the format of a piece of data. In HTTP, the media type describes the format of the message body. A media type consists of two strings: type and subtype. For example:

    • Text/html
    • Image/png
    • Application/json

When a 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.
When an HTTP message contains an entity, the Content-type (content type) header specifies the format of the message body. This is the content that tells the receiver how to parse the body of the message.

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

http/1.1 Okcontent-length:95267content-type:image/png

When the client is 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:
When a client sends a request message, it may include an accept header. The Accept header tells the server what type of media the client wants to get from the server. For example:

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

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

In Web APIs, the media type determines how Web API serializes and deserializes the HTTP message body. There is built-in support for XML, JSON, and form-urlencoded data, and you can support additional media types by writing a Media formatter.
In the Web API, the media type determines how the Web API serializes and serializes the HTTP message body. Built-in support for XML, JSON, and URL-encoded form data. Also, you can support additional media types by writing media formatter (Formatter).

To create a media formatter, derive from one of these classes:
In order to create a media formatter, you derive from the following classes:

    • Mediatypeformatter. This class uses asynchronous read and write methods.
      Mediatypeformatter. This class uses asynchronous read and write methods.
    • Bufferedmediatypeformatter. This class derives from Mediatypeformatter but wraps the asynchronous Read/write methods inside synchronous Metho Ds.
      Bufferedmediatypeformatter. This class derives from Mediatypeformatter, but encapsulates the asynchronous read-write method in a synchronous method.

Deriving from Bufferedmediatypeformatter are simpler, because there is no asynchronous code, but it also means the calling Thread can block during I/O.
Deriving from Bufferedmediatypeformatter is simpler because there is no async code, but it also means that threads may be blocked during I/O.

6.1.2 Creating a Media Formatter
6.1.2 Creating a Media formatter

The following example shows a media type formatter that can serialize a Product object to a comma-separated values (CSV) F Ormat. 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:
The following example shows a media type formatter that serializes the product object into a comma-separated value (CSV) format. The example uses the product type defined in the Create a crud Web API (Section 2.1 of this tutorial series) tutorial. The following is the definition of the Product object:

namespace productstore.models{public    class Product    {public        int Id {get; set;}        public string Name {get; set;}        public string Category {get; set;}        Public decimal price {get; set;}}    }

To implement a CSV formatter, define a class this derives from Bufferedmediatypeformater:
To implement the CSV formatter, define a class that derives from Bufferedmediatypeformater:

namespace productstore.formatters{    using System;    Using System.Collections.Generic;    Using System.IO;    Using System.Net.Http.Formatting;    Using System.Net.Http.Headers;    Using Productstore.models;
public class Productcsvformatter:bufferedmediatypeformatter { }}

In the constructor, add the media types that the formatter supports. In this example, the formatter supports a single media type, "Text/csv":
In its constructor, you add a media type that the formatter supports. In this example, the formatter only supports a single media type: "Text/csv":

Public Productcsvformatter () {    //ADD the supported media type.    Add the supported media type    Supportedmediatypes.add (new Mediatypeheadervalue ("Text/csv"));}

Override the Canwritetype method to indicate which types the formatter can serialize:
Override this Canwritetype method to indicate which type the formatter can serialize:

public override bool Canwritetype (System.Type type) {    if (type = = typeof (Product))    {        return true;    }    else    {        Type enumerabletype = typeof (Ienumerable<product>);        return Enumerabletype.isassignablefrom (type);    }}

In this example, the formatter can serialize single product objects as well as collections of Product objects.
In this example, the formatter can serialize a single Product object and a collection of product objects.

Similarly, override the Canreadtype method to indicate which types the formatter can deserialize. In this example, the formatter does isn't support deserialization, so the method simply returns false.
Accordingly, override the Canreadtype method to indicate what type the formatter can deserialize. In this case, the formatter does not support deserialization, so the method simply returns false.

protected override bool Canreadtype (type type) {    return false;}

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.
Finally, rewrite the WriteToStream method. By writing a type into a stream, the method serializes the type. You can also override the ReadFromStream method if your formatter supports deserialization.

public override void WriteToStream (type type, object value, Stream stream, Httpcontentheaders contentheaders) {usin G (var writer = new StreamWriter (stream)) {var products = value as ienumerable<product>;
if (products = null) {foreach (var product in products) {Writeitem (product, writer); }} else {var singleproduct = value as Product; if (singleproduct = = null) {throw new InvalidOperationException ("Cannot serialize type"); } writeitem (singleproduct, writer); }} stream. Close ();} Helper methods for serializing products to CSV format. The helper method that serializes product to CSV format private void Writeitem (product product, StreamWriter writer) {writer. WriteLine ("{0},{1},{2},{3}", Escape (product. ID), Escape (product. Name), Escape (product. Category), Escape (product. Price));}
Static char[] _specialchars = new char[] {', ', ' \ n ', ' \ R ', ' '};
private string Escape (object o) {if (o = = null) {return ""; } string field = O.tostring (); if (field. IndexOfAny (_specialchars)! =-1) {return String.Format ("\" {0}\ "", field. Replace ("\" "," \ "\") "); } else return field;}
6.1.4 Adding the Media Formatter
6.1.4 Adding a media formatter

To add a media type formatter to the Web API pipeline with the Formatters property on the Httpconfiguration object.
In order to add the media type formatter to the Web API pipeline, use the Formatters property on the Httpconfiguration object.

public static void Configureapis (Httpconfiguration config) {    config. Formatters.add (New Productcsvformatter ()); }

For ASP. Hosting, add this function to the Global.asax file and call it from the Application_Start method.
For ASP. NET hosting, add this function to the Global.asax file and call it through the Application_Start method.

protected void Application_Start () {    configureapis (globalconfiguration.configuration);
// ...}

Now if a client specifies "Text/csv" in the Accept header, the server would return the data in CSV format.
Now, if the client specifies "Text/csv" in the Accept header, the server returns data in CSV format.

The following example uses HttpClient to get the CSV data and write it to a file:
The following example uses HttpClient to get the CSV data and write it to a file:

HttpClient client = new HttpClient ();
Add the Accept header//adds the Accept header client.DefaultRequestHeaders.Accept.Add (new Mediatypewithqualityheadervalue (" Text/csv "));
Get the result and write it to a file.//(port 9000 was just an example port number.) Get the result and write it to the file//(port number 9,000 is only a sample port number) string result = client. Getstringasync ("http://localhost:9000/api/product/"). Result; System.IO.File.WriteAllText ("products.csv", result);

"ASP. NET Web API Tutorial" 6.1 Media Formatter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.