使用Jil序列化JSON提升Asp.net web api 性能
JSON序列化无疑是Asp.net web api 里面性能提升最重要的一环。 通天塔
在Asp.net web api 里面我们可以插入自定义的MediaTypeFormatter(媒体格式化器),
说白了就是根据HTTP content-type application/json
来判断采用哪种媒体格式化器

具体实现,记得要引入Jil包
public class JilFormatter : MediaTypeFormatter
{
private readonly Options _jilOptions;
private MethodInfo _method; public JilFormatter()
{
//要序列化的时间格式
_jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601);
//媒体类型
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
//加入 UTF8Encoding 编码
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
//加入 UnicodeEncoding 编码
SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true)); }
//判断是否反序列化类型
public override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return true;
}
//判断是否序列化类型
public override bool CanWriteType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return true;
} // 异步反序列化一个指定类型的对象。
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
return Task.FromResult(DeserializeFromStream(type, readStream));
} private object DeserializeFromStream(Type type, Stream readStream)
{
try
{
using (var reader = new StreamReader(readStream))
{
return JSON.Deserialize(reader, type, _jilOptions);
}
}
catch
{
return null;
}
} // 异步序列化一个指定类型的对象。
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
{
var streamWriter = new StreamWriter(writeStream);
JSON.Serialize(value, streamWriter, _jilOptions);
streamWriter.Flush();
return Task.FromResult(writeStream);
}
}
加入到媒体格式化器集合中
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 } );
GlobalConfiguration.Configuration.Formatters[] = new JilFormatter();
}
}
控制类
public class HomeController : ApiController
{
public static List<Market> Markets = new List<Market>(); public HomeController()
{ } static HomeController()
{
Markets.Add(new Market { Id = , Name = "", DateTimeNow = DateTime.Now });
Markets.Add(new Market { Id = , Name = "", DateTimeNow = DateTime.Now });
Markets.Add(new Market { Id = , Name = "", DateTimeNow = DateTime.Now });
Markets.Add(new Market { Id = , Name = "", DateTimeNow = DateTime.Now });
Markets.Add(new Market { Id = , Name = "", DateTimeNow = DateTime.Now });
}
public IEnumerable<Market> Get()
{
return Markets;
}
public HttpResponseMessage Post([FromBody]Market value)
{
Markets.Add(value);
return new HttpResponseMessage(HttpStatusCode.OK);
} public HttpResponseMessage Put(int id, [FromBody]Market value)
{
var market = Markets.Where(x => x.Id == id).FirstOrDefault();
if (market == null)
return new HttpResponseMessage(HttpStatusCode.NotFound); market.Name = value.Name;
return new HttpResponseMessage(HttpStatusCode.OK);
} public HttpResponseMessage Delete(int id)
{
var result = Markets.Remove(Markets.Where(x => x.Id == id).FirstOrDefault());
return result
? new HttpResponseMessage(HttpStatusCode.Accepted)
: new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
我们通过postman访问

我们在post一个实体

我们在get一下

已经可以看见刚才post的实体了。
源码:http://pan.baidu.com/s/1i3o6KD3
Asp.net Mvc vnext 系列 http://www.cnblogs.com/liek/p/4634294.html
得到你的肯定是我最大的动力!
使用Jil序列化JSON提升Asp.net web api 性能的更多相关文章
- 8 种提升 ASP.NET Web API 性能的方法
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- 六种简单方法提升ASP.NET Web API性能
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- 8种提升ASP.NET Web API性能的方法
英文原文:8 ways to improve ASP.NET Web API performance ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没 ...
- [转载]8 种提升 ASP.NET Web API 性能的方法
http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance 英文原文:8 ways to improve A ...
- 8 种提升 ASP.NET Web API 性能的方法 (转)
出处:http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance ASP.NET Web API 是非常棒的 ...
- 8 种提升ASP.NET Web API性能的方法
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
- 8种提升 ASP.NET Web API 性能的方法
- Jil序列化JSON
使用Jil序列化JSON提升Asp.net web api 性能 JSON序列化无疑是Asp.net web api 里面性能提升最重要的一环. 在Asp.net web api 里面我们可以插入 ...
- ASP.NET Web API 提升性能的方法实践
ASP.NET Web API 是非常棒的技术.编写 Web API 十分容易,以致于很多开发者没有在应用程序结构设计上花时间来获得很好的执行性能. 在本文中,我将介绍8项提高 ASP.NET Web ...
随机推荐
- iOS TPKeyboardAvoiding自动识别键盘的高度
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicatio ...
- Mysql主从库同步错误:1062 Error 'Duplicate entry '1438019'
mysql主从库同步错误:1062 Error 'Duplicate entry '1438019' for key 'PRIMARY'' on query mysql主从库在同步时会发生1062 L ...
- 定时器 NSTimer 和 CADisplayLink
NSTimer *timer; CADisplayLink *caDisplayLink; int timeCount; - (void)viewDidLoad { [super viewDidLoa ...
- NSDictionary
// ------------------------------字典------------------------------------------------- NSDictionary *d ...
- Tomcat类加载器机制
Tomcat为什么需要定制自己的ClassLoader: 1.定制特定的规则:隔离webapp,安全考虑,reload热插拔 2.缓存类 3.事先加载 要说Tomcat的Classloader机制,我 ...
- editplus3运行Python程序
editplus3是一款不错的编辑器,他可以编译,运行java,php等各种程序,现把他运行Python程序的方法贴出来,首先得安装python,然后打开editplug3,工具——配置用户工具——组 ...
- Lintcode: Segment Tree Modify
For a Maximum Segment Tree, which each node has an extra value max to store the maximum value in thi ...
- G面经prepare: set difference
给你A{1,2,3,4,4,5}, B{2,4},求A-B={1,3,4,5},很简单. visit 1 只用一个HashMap package TwoSets; import java.util.* ...
- 记录把方法添加到 JavaScript 对象不明白的地方
<!DOCTYPE html> <html> <body> <script> function person(firstname,lastname,ag ...
- extjs实现简单的多文件上传(不借助任何插件),以及包含处理上传大文件的错误的各种处理办法
在extjs的学习过程中,有遇到过有关多文件上传的问题,但是网上的大多数都是专门的去实现多文件上传而去做的组件之类的,没有特别简单的方式,于是小白便做了下面的内容,只是通过动态的去添加extjs的自带 ...