标签:
1. 在AspNet WebApi中,MediaTypeFormatter的作用就是执行数据的格式化,简单说就是执行CLR对象的序列化操作,将CLR对象转换为可在HTTP中传输的数据格式对象,例如Json,XML等.
AspNet/WebApi 默认自带了四种MediaTypeFormatter格式: (我们只关注JSON和XML)
其他的可以通过HttpConfiguration的Formatters属性,例如:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); foreach (var formatter in config.Formatters) { System.Diagnostics.Debug.WriteLine("Name:" + formatter.GetType().Name); } } } + 输出 Name:JsonMediaTypeFormatter Name:XmlMediaTypeFormatter Name:FormUrlEncodedMediaTypeFormatter Name:JQueryMvcFormUrlEncodedFormatter
2. 选择合适的MediaTypeFormatter,我们基于下面几种情况考虑
3. 基于mediaTypeMapping来实现选择合适的MediaTypeFormatter
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //http://xxx?format=json config.Formatters.JsonFormatter.MediaTypeMappings.Add( new System.Net.Http.Formatting.QueryStringMapping("format", "json", "application/json")); //http://xxxx?format=xml config.Formatters.XmlFormatter.MediaTypeMappings.Add( new System.Net.Http.Formatting.QueryStringMapping("format", "xml", "application/xml")); } + 请求输入 + 请求: http://localhost:6128/api/values?format=json Json输出: [{"Name":"VISON ME","Email":"Visonme@aliyun.com"},{"Name":"cnblog","Email":"cnblog@cnblog.com"}] 请求 :http://localhost:6128/api/values?format=xml xml输出: This XML file does not appear to have any style information associated with it. The document tree is shown below. <ArrayOfUser xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MediaTypeFormatDemo.Controllers"> <User> <Email>Visonme@aliyun.com</Email> <Name>VISON ME</Name> </User> <User> <Email>cnblog@cnblog.com</Email> <Name>cnblog</Name> </User> </ArrayOfUser>
config.Formatters.JsonFormatter.MediaTypeMappings.Add( new System.Net.Http.Formatting.RequestHeaderMapping("x-media-json" ,"json",StringComparison.OrdinalIgnoreCase ,false,"application/json")));
4.定制mediaTypeMapping
mediaTypeMapping是可定制,可以通过继承MediaTypeMapping抽象类,实现TryMatchMediaType方法,例如:
public class CustomMediaTypeMapping : System.Net.Http.Formatting.MediaTypeMapping { public CustomMediaTypeMapping() : base(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")) { //do something } public override double TryMatchMediaType(System.Net.Http.HttpRequestMessage request) { //如果header中包含x-media-XXX字段执行json formatter if (request.Headers.Contains("x-media-xxx")) { return 1.0; } return 0.0; } } + 注册 + config.Formatters.JsonFormatter.MediaTypeMappings.Add( new CustomMediaTypeMapping());
5.定制专属MediaTypeformatter
关于这个话题,可以参考这篇文章 Custom MediaTypeFormatter
标签:
原文地址:http://www.cnblogs.com/visonme/p/4684496.html