Media Formatters in ASP.NET Web API 2
原文:http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
1. 网络媒体类型
媒体类型,也叫作MIME类型,表示数据的格式。在HTTP中,MIME描述了消息体的格式。
- MIME类型有两个字符串组成——类型和子类型。例如:
text/html
image/png
application/json
- 当HTTP消息包含一个数据体时,Content-Type 头部指出了数据体的格式。这告诉接收者怎么解析消息体。例如,如果HTTP响应包含一个PNG图片,那响应可能包含以下头部。
HTTP/1.1 200 OK
Content-Length: 95267
Content-Type: image/png
- 客户端可以包含Accept头部来发起一个请求。Accept头部告诉服务器客户端想要什么类型的MIME类型。例如:
Accept: text/html,application/xhtml+xml,application/xml
这个头部告诉服务器,客户端想要HTML,XHTML,或者XML。
- MIME类型决定了WEB API怎么序列化和反序列化HTTP的消息体。WEB API有内置的MIME,支持XML,JSON,BSON,以及form-urlencoded数据,也可以通过自定义一个媒体格式。
为了创建一个MIME格式,从以下其中一个类派生:
MediaTypeFormatter. 这个类使用异步的读写方法。
BufferedMediaTypeFormatter. 这个类从MediaTypeFormatter 派生,但是使用同步的读写方法。
2. 示例:创建一个CSV媒体格式
Steps:
- 创建一个ProductCsvFormatter
- 构造函数添加支持的媒体类型
- 重写CanWriteType,表明可以序列化的类型
- 重写CanReadType,表明可以反序列化的类型
- 重写WriteToStream,序列化的真正实现
- 将媒体格式添加到WEB API管道
- 添加字符编码支持,支持UTF-8,iso-8859-1
- 增加测试代码
ProductCsvFormatter 代码片段:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using WebApiPractice.Models;
namespace WebApiPractice.Formatters
{
//http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
//Step1
public class ProductCsvFormatter: BufferedMediaTypeFormatter
{
public ProductCsvFormatter()
{
//Step2
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
//Step7
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"));
}
//Step3
public override bool CanWriteType(Type type)
{
if(type == typeof(Product))
{
return true;
}
Type enumerableType = typeof(IEnumerable<Product>);
return enumerableType.IsAssignableFrom(type);
}
//Step4
public override bool CanReadType(Type type)
{
return false;
}
//Step5
public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
{
//Step7
Encoding effectiveEncoding = SelectCharacterEncoding(content.Headers);
using (var writer = new StreamWriter(writeStream, effectiveEncoding))
{
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);
}
}
}
// Helper methods for serializing Products 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)
{
// Delimit the entire field with quotes and replace embedded quotes with "".
return String.Format("\"{0}\"", field.Replace("\"", "\"\""));
}
else return field;
}
}
}
WebApiConfig代码片段:
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using WebApiPractice.Formatters;
namespace WebApiPractice
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// 将 Web API 配置为仅使用不记名令牌身份验证。
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Step6,加入web api管道
config.Formatters.Add(new ProductCsvFormatter());
}
}
}
测试代码:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
namespace WebApiPractice
{
public class WebApiRequestHelper
{
public void Start()
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv", 1));
var t = httpClient.GetStringAsync("http://localhost:60865/api/products");
t.Wait();
System.Diagnostics.Debug.WriteLine(t.Result);
Console.WriteLine(t.Result);
}
}
}
测试结果:
1,Tomato Soup,Groceries,1
2,Yo-yo,Toys,3.75
3,Hammer,Hardware,16.99
Media Formatters in ASP.NET Web API 2的更多相关文章
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- 【ASP.NET Web API教程】6.1 媒体格式化器
http://www.cnblogs.com/r01cn/archive/2013/05/17/3083400.html 6.1 Media Formatters6.1 媒体格式化器 本文引自:htt ...
- 【ASP.NET Web API教程】6 格式化与模型绑定
原文:[ASP.NET Web API教程]6 格式化与模型绑定 6 Formats and Model Binding 6 格式化与模型绑定 本文引自:http://www.asp.net/web- ...
- Asp.Net Web API 2第十二课——Media Formatters媒体格式化器
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本教程演示如何在ASP.N ...
- ASP.NET Web API 2.1支持Binary JSON(Bson)
ASP.NET Web API 2.1内建支持XML.Json.Bson.form-urlencoded的MiME type,今天重点介绍下Bson.BSON是由10gen开发的一个数据格式,目前主要 ...
- ASP.NET Web API系列教程目录
ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...
- 【ASP.NET Web API教程】6.3 内容协商
本文是Web API系列教程的第6.3小节 6.3 Content Negotiation 6.3 内容协商 摘自:http://www.asp.net/web-api/overview/format ...
- Asp.Net Web API 2第十四课——Content Negotiation(内容协商)
前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...
- Replace JSON.NET with ServiceStack.Text in ASP.NET Web API
Because ServiceStack.Text performs much better I recently stumbled across a comparison of JSON seria ...
随机推荐
- Spring3.0目录
(1)Spring 入门知识 (2)IoC/DI基本思想的演变 (3)深入理解IoC/DI (4)Spring的简单demo
- 【Solr】新建core后,启动服务访问web报错 HTTP Status 503
新建core collection2后,启动solr服务,访问solr web界面报错. HTTP Status 503 - Server is shutting down or failed to ...
- 如何快速正确的安装 Ruby, Rails 运行环境---------------转载
https://ruby-china.org/wiki/install_ruby_guide 这上面有全部教程, 亲测可用
- PHP判断远程文件是否存在
<?php /* 函数:remote_file_exists 功能:判断远程文件是否存在 参数: $url_file -远程文件URL 返回:存在返回true,不存在或者其他原因返回false ...
- C和指针 第十章 结构和联合 (一)
结构体: 聚合数据类型是指,能够同时存储超过一个的单独数据,C语言中有两个聚合数据类型,数组和结构体.数组中储存的类型必须相同,元素通过下标和指针引用来访问的. 结构体也是一些值的集合,但是结构体中每 ...
- 清理系统 cmd
echo 正在清除系统垃圾文件,请稍等......del /f /s /q %systemdrive%*.tmpdel /f /s /q %systemdrive%*._mpdel /f /s /q ...
- Ural 1057 Amount of Degrees
Description 问[L,R]中有多少能表示k个b次幂之和. Sol 数位DP. 当2进制时. 建出一个二叉树, \(f[i][j]\) 表示长度为 \(i\) 有 \(j\) 个1的个数. 递 ...
- HTML5和HTML4的主要区别 [转]
原文:http://www.cnblogs.com/jiangyehu1110/archive/2013/07/10/3182277.html 1. HTML5标准还在制定中 这头一个不同之处显而易见 ...
- XHPROF相关内容
定义入口文件 define('XHPROF_OPEN', 0); define('XHPROF_ROOT', '/home/www/xhprof/'); // 开启调试模式 建议开发阶段开启 部署阶段 ...
- C# Bitmap deep copy
今天在研究一个关于 Bitmap deep copy 的问题, 经过一系列的查询,在StackOverFlow上面找到了答案,遂记录下来: public static Bitmap DeepCopyB ...