The Web API is built in to support the MIME type of XML, JSON, BSON, and form-urlencoded.
Create a custom MIME type to inherit one of the following classes:
- Mediatypeformatter This class uses asynchronous read/write methods
- Bufferedmediatypeformatter This class inherits from Mediatypeformatter, but it uses synchronous read/write methods
Customize a MIME type, as follows:
Public classProductcsvformatter:bufferedmediatypeformatter { PublicProductcsvformatter () {//Media TypeSupportedmediatypes.add (NewMediatypeheadervalue ("Text/csv")); //Supported character setsSupportedencodings.add (Encoding.GetEncoding ("iso-8859-1")); Supportedencodings.add (NewUTF8Encoding (encodershouldemitutf8identifier:false)); } //indicates which type of formatter can be serialized, Public Override BOOLcanwritetype (Type type) {//supports serialization of a collection of product objects and product objects if(Type = =typeof(Product))return true; Else{Type Enumerabletype=typeof(ienumerable<product>); returnenumerabletype.isassignablefrom (type); } } //indicates which object can be deserialized Public Override BOOLcanreadtype (Type type) {//No deserialization is currently required so return false return false; } //serializes an object and writes to the stream, and overloads the ReadFromStream method if it supports deserialization Public Override voidWriteToStream (Type type,Objectvalue, System.IO.Stream writestream, System.Net.Http.HttpContent content) {Encoding effectiveencoding=selectcharacterencoding (content. Headers); using(varwriter =NewStreamWriter (Writestream, effectiveencoding)) { varProducts = value asIenumerable<product>; if(Products! =NULL) { foreach(varProductinchProducts ) {Writeitem (product, writer); } } Else { varSingleproduct = value asProduct; if(Singleproduct = =NULL) Throw NewInvalidOperationException ("cannot serialize type"); Writeitem (singleproduct, writer); } } } Private voidWriteitem (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 stringEscape (Objecto) {if(O = =NULL) return ""; stringfield =o.tostring (); if(field. IndexOfAny (_specialchars)! =-1) { returnString.Format ("\ "{0}\"", field. Replace ("\"","\"\"")); } Else returnfield; } }
Public Static voidRegister (httpconfiguration config) {//Web API Configuration and Services//Web API RoutingCONFIG. Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional}); //to add a custom MIME typeConfig. Formatters.add (NewProductcsvformatter ()); }
to specify Content-type when impersonating a request request
WEBAPI2 official website Study record---Media formatters