WEBAPI2 official website Study record---Media formatters

Source: Internet
Author: User

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

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.