ASP.NET Web API MediaTypeFormatter
MediaTypeFormatter提供了HTTP Request body data與.Net類型之間的無縫轉(zhuǎn)換。
什么是MediaType
Media Type指的是HTTP header中的content-type,它定義了在HTTP Body中的數(shù)據(jù)的格式。Media Type也用于Http RequestHeader中的Accept頭,表明改Request期望收到的Response的body的格式。
你可以使用標(biāo)準(zhǔn)的media type,比如application/json, application/xml。你也可以定義自己的media type.
什么是MediaTypeFormatter
MediaTypeFormatter用于在Http Body和.Net之間進(jìn)行轉(zhuǎn)換。
所有的MediaTypeFormatter都繼承自抽象類MediaTypeFormatter
public abstract class MediaTypeFormatter {// propertiespublic Collection<MediaTypeHeaderValue> SupportedMediaTypes { get; private set; }public Collection<Encoding> SupportedEncodings { get; private set; }public Collection<MediaTypeMapping> MediaTypeMappings { get; private set; }// methodspublic virtual Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger){// to be overriden by base class }public virtual Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext){// to be overriden by base class }public abstract bool CanReadType(Type type);public abstract bool CanWriteType(Type type); }
要定義自己的MediaTypeFormatter,只需要實(shí)現(xiàn)上述抽象類即可。
這里有詳細(xì)的例子
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
怎么使用自定義的formatter
要把一個(gè)media type formatter加入Web API Pipeline,
public static void ConfigureApis(HttpConfiguration config) {config.Formatters.Add(new ProductCsvFormatter()); }什么時(shí)候Web API Framework會(huì)用到MediaTypeFormatter
我們前面說過,media type主要用于HTTP Request/Response header中的content-type,和HTTP Request header中的Accept。
HTTP Request/Response header中的content-type
當(dāng)Web API接收到HTTP Request請(qǐng)求,并且需要讀取body信息時(shí)(比如,使用FromBody屬性),Web API會(huì)檢查content-type的類型,然后使用已注冊(cè)的formatter去deserialize。
HTTP Request header中的Accept
假設(shè)我們有一個(gè)Product類
[DataContract(Name = "Product", Namespace = "http://www.azure.com")]public class Product{[DataMember]public int Id { get; set; }[DataMember]public string Name { get; set; }[DataMember]public string Category { get; set; }[DataMember]public decimal Price { get; set; }}以及一個(gè)Web API的controller
public HttpResponseMessage Get() {var product = new Product() { Id = 1, Name = "Gizmo", Category = "Widgets", Price = 1.99M };return Request.CreateResponse(HttpStatusCode.OK, product); }這個(gè)controller返回一個(gè)HttpResponseMessage對(duì)象,里面包含一個(gè)product。
此時(shí),Web API會(huì)檢查該Request的Header中Accept的內(nèi)容,然后調(diào)用相應(yīng)的formatter去序列號(hào)product對(duì)象。
我們可以使用fiddler發(fā)送以下request
User-Agent: Fiddler Host: localhost:9664 Accept: application/xml那么我們得到的response是
HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/xml; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sat, 18 Oct 2014 08:35:21 GMT Content-Length: 187<Product xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.azure.com"><Category>Widgets</Category><Id>1</Id><Name>Gizmo</Name><Price>1.99</Price></Product>注意Content-Type,以及body的格式。
如果我們發(fā)送以下request
User-Agent: Fiddler Host: localhost:9664 Accept: application/json?
我們得到的response是
HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcZWR3YW5nXGRvY3VtZW50c1x2aXN1YWwgc3R1ZGlvIDIwMTNcUHJvamVjdHNcV2ViQXBwVGVzdFxXZWJBcHBUZXN0XGFwaVx2YWx1ZXM=?= X-Powered-By: ASP.NET Date: Sat, 18 Oct 2014 09:22:45 GMT Content-Length: 57{"Id":1,"Name":"Gizmo","Category":"Widgets","Price":1.99}?
Web API使用XmlMediaTypeFormatter處理xml media type。XmlMediaTypeFormatter默認(rèn)使用DataContractSerializer進(jìn)行序列化。
使用JsonMediaTypeFormatter處理json media type。JsonMediaTypeFormatter默認(rèn)使用Json.net進(jìn)行序列化。
?
轉(zhuǎn)載于:https://www.cnblogs.com/wangguangxin/p/4033384.html
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Web API MediaTypeFormatter的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【资源汇总分享】Android开发资源汇
- 下一篇: SQLite中不支持的sql语法