Web API内建支持XML、JSON、BSON、和form-urlencoded的MiME type。

创建的自定义MIME类型要继承一下类中的一个:

自定义一个MIME类型,如下:

  public class ProductCsvFormatter:BufferedMediaTypeFormatter
{
public ProductCsvFormatter()
{
//媒体类型
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
//支持的字符集
SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"));
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier:false)); }
//指示哪种类型 格式化器可以进行序列化,
public override bool CanWriteType(Type type)
{//支持序列化翻个Product对象和Product对象集合
if (type == typeof(Product))
return true;
else
{
Type enumerableType = typeof(IEnumerable<Product>);
return enumerableType.IsAssignableFrom(type);
}
}
//指示哪个对象可以被反序列化
public override bool CanReadType(Type type)
{//目前不需要反序列化 所以返回false
return false;
}
//序列化对象并写入流,如果支持反序列化还需要重载ReadFromStream方法
public override void WriteToStream(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content)
{
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);
}
}
}
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) != -)
{
return String.Format("\"{0}\"", field.Replace("\"", "\"\""));
}
else
return field; }
}
 public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//添加自定义的MIME类型
config.Formatters.Add(new ProductCsvFormatter());
}

模拟请求如图:请求时要指定Content-Type

或者在控制台模拟一个请求:

         static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));
string result = client.GetStringAsync("http://localhost:53330/api/products/").Result;
System.IO.File.WriteAllText("d:\\products.csv", result);
}

WebApi2官网学习记录---Media Formatters的更多相关文章

  1. WebApi2官网学习记录---Content Negotiation

    Content Negotiation的意思是:当有多种Content-Type可供选择时,选择最合适的一种进行序列化并返回给client. 主要依据请求中的Accept.Accept-Charset ...

  2. WebApi2官网学习记录---BSON

    BSON 是轻量级的,能够进行快速查询和高效的解码/编码.BSON方便查询是由于elements的前面都有一个表示长度的字段,所以解释器可以快速跳过这个elements:高效的解码/编码是因为nume ...

  3. WebApi2官网学习记录---Configuring

    Configuration Settings WebAPI中的configuration settings定义在HttpConfiguration中.有一下成员: DependencyResolver ...

  4. WebApi2官网学习记录---JSON与XML的序列化

    JSON序列化: WebAPI的默认序列库使用的是Json.NET,可以在Globally中配置使用DataContractJsonSerializer 进行序列化 protected void Ap ...

  5. WebApi2官网学习记录---Cookie

    Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...

  6. WebApi2官网学习记录---批量处理HTTP Message

    原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...

  7. WebApi2官网学习记录---Html Form Data

    HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...

  8. WebApi2官网学习记录--HttpClient Message Handlers

    在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...

  9. WebApi2官网学习记录--HTTP Message Handlers

    Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...

随机推荐

  1. (转)弹出窗口lhgDialog API文档

    应用到你的项目 如果您使用独立版本的lhgDialog窗口组件,您只需在页面head中引入lhgcore.lhgdialog.min.js文件,4.1.1+版本做了修改可以和jQuerya库同时引用, ...

  2. arcgis server "System.Web.Services.Protocols.SoapException: Error processing server request".

    在 Arcgis Server 10中创建第一个程序,运行的时候就报错:System.Web.Services.Protocols.SoapException: Error processing se ...

  3. SQL Server中的临时表和表变量 Declare @Tablename Table

    在SQL Server的性能调优中,有一个不可比面的问题:那就是如何在一段需要长时间的代码或被频繁调用的代码中处理临时数据集?表变量和临时表是两种选择.记得在给一家国内首屈一指的海运公司作SQL Se ...

  4. poj1850

    是因为我好久不刷题了吗,这个题竟然做了俩小时,好几个思路都被推翻 用dp数组预处理出范围是a->a+x字符y长度有多少种递增串 然后例如def首先求a__有多少种情况那么自然后面就是只有b即dp ...

  5. uva 10260 - Soundex

    题目:编码翻译,有些字母有对应的数字,有的没有,如果连续对应的数字相同只输出一个. #include <iostream> #include <cstdlib> #includ ...

  6. 作业:汽车查询--弹窗显示详情,批量删除 php做法(0521)

    作业:显示以下界面: 作业要求: 1.查看详细信息,以弹窗的形式显示,使用ajax2.批量删除 一.主页面: <!DOCTYPE html PUBLIC "-//W3C//DTD XH ...

  7. Python 基础教程中的问题及解决方案(1)

    1. 在ubuntu中,调用终端时如: f = open('/home/theone/test_input.txt', 'r') 中的txt格式文本不能加后缀 正确的应为:  f = open('/h ...

  8. 微信分享jsdk接口

    HTML文件 <!DOCTYPE html><html><head> <meta charset="utf-8"> <titl ...

  9. production stage

    MP:mass production 批量生产 DV design verification 设计验证 EV engineering verification 工程样品验证 PV process ve ...

  10. List容器

    List 容器 list是C++标准模版库(STL,Standard Template Library)中的部分内容.实际上,list容器就是一个双向链表,可以高效地进行插入删除元素. 使用list容 ...