Objective
Before reading this article, you can also go to the ASP. NET Web API 2 series navigation to view http://www.cnblogs.com/aehyok/p/3446289.html
This tutorial demonstrates how to support additional media formats in the ASP.
Media types for Internet media types--internet
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 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 picture, the response might have the following header.
http/1.1 Okcontent-length:95267content-type:image/png
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
The header tells the server that the client wants to get HTML, XHTML, or XML.
In the Web API, the media type determines how the Web API serializes and deserializes 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).
In order to create a media formatter, you derive from the following classes:
- Mediatypeformatter. This class uses asynchronous read and write methods.
- Bufferedmediatypeformatter. This class derives from Mediatypeformatter, but encapsulates the asynchronous read-write method in a synchronous method.
Deriving from Bufferedmediatypeformatter is simpler because there is no async code, but it also means that threads may be blocked during I/O.
Creating a media formatter--creating a medium formatter
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 ASP.--crud operation Http://www.cnblogs.com/aehyok/p/3434578.html in the Net Web API 2 lesson two. 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 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 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 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 a single Product object and a collection of product objects.
Accordingly, override the Canreadtype method to indicate which 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, 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 ', ' '};p rivate 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;}
Adding the media formatter--add a medium formatter
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. 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 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:
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 are just an example por T 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. 2 12th Lesson--media formatters Media Formatter