让Web API支持Protocol Buffers
简介
现在我们Web API项目基本上都是使用的Json作为通信的格式,随着移动互联网的兴起,Web API不仅其他系统可以使用,手机端也可以使用,但是手机端也有相对特殊的地方,网络通信除了wifi,还有蜂窝网络比如2G/3G,当手机处于这种网络环境下并且在一些偏僻或者有建筑物阻挡的地方,网络会变得非常差,之前我有测试过ProtoBuf和Json在序列化和反序列化上性能的对比,通过测试发现ProtoBuf在序列化和反序列化以及序列化后字节的长度和其他的框架相比都有很大的优势,所以这篇文章准备让Web API也支持Protocol Buffers。
实现
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}", //修改路由规则
defaults: new { id = RouteParameter.Optional }
); config.Formatters.Add(new ProtoBufFormatter());
}
public class UserController : ApiController
{ /// <summary>
/// 注册用户
/// </summary>
/// <param name="userDto"></param>
/// <returns></returns>
public string Regist(UserDto userDto)
{
if (!string.IsNullOrEmpty(userDto.UserName) && !string.IsNullOrEmpty(userDto.Password))
{
return "regist success";
}
return "regis error";
} //登陆
public string Login(UserLoginDto userLoginDto)
{
if (userLoginDto.UserName == "sa")
{
return "login success";
}
return "loign fail";
} /// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="userName"></param>
/// <returns></returns>
public UserDto Get(string userName)
{
if (!string.IsNullOrEmpty(userName))
{
return new UserDto()
{
UserName = "sa",
Password = "",
Subscription = new List<string>() {"news", "picture"}
};
}
return null;
}
}
[ProtoContract]
public class UserDto
{
[ProtoMember()]
public string UserName { get; set; } [ProtoMember()]
public string Password { get; set; } [ProtoMember()]
public List<string> Subscription { get; set; }
} [ProtoContract]
public class UserLoginDto
{
[ProtoMember()]
public string UserName { get; set; } [ProtoMember()]
public string Password { get; set; }
}

static void Main(string[] args)
{
var client = new HttpClient { BaseAddress = new Uri("http://192.168.16.9:8090/") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); Regist(client);
Console.WriteLine("===================================");
Login(client);
Console.WriteLine("===================================");
GetUser(client);
Console.WriteLine("===================================");
Console.ReadLine();
} private static void Regist(HttpClient client)
{
//注册
var userDto = new UserDto()
{
UserName = "sa",
Password = "",
Subscription = new List<string>() { "news", "picture" }
}; HttpResponseMessage response = client.PostAsync("api/User/Regist", userDto, new ProtoBufFormatter()).Result; if (response.IsSuccessStatusCode)
{
var p = response.Content.ReadAsAsync<string>(new[] { new ProtoBufFormatter() }).Result;
Console.WriteLine(p);
}
} private static void Login(HttpClient client)
{ //登陆
var userlogin = new UserLoginDto()
{
UserName = "sa",
Password = "",
}; HttpResponseMessage response = client.PostAsync("api/User/login", userlogin, new ProtoBufFormatter()).Result;
if (response.IsSuccessStatusCode)
{
var p = response.Content.ReadAsAsync<string>(new[] { new ProtoBufFormatter() }).Result;
Console.WriteLine(p);
}
} private static void GetUser(HttpClient client)
{ HttpResponseMessage response = client.GetAsync("api/User/Get?userName=sa").Result; if (response.IsSuccessStatusCode)
{
var p = response.Content.ReadAsAsync<UserDto>(new[] { new ProtoBufFormatter() }).Result; Console.WriteLine(p.UserName + " " + p.Password);
foreach (var s in p.Subscription)
{
Console.WriteLine(s);
}
}
}

让Web API支持Protocol Buffers的更多相关文章
- Go 支持Protocol Buffers的配置
安装 protoc (The protocol compiler)是由C++写的,支持的 C++.Java.Python.Objective-C.C#.JavaNano.JavaScript.Ruby ...
- 通过扩展让ASP.NET Web API支持JSONP
同源策略(Same Origin Policy)的存在导致了"源"自A的脚本只能操作"同源"页面的DOM,"跨源"操作来源于B的页面将会被拒 ...
- 通过扩展让ASP.NET Web API支持W3C的CORS规范
让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...
- 让ASP.NET Web API支持POST纯文本格式(text/plain)的数据
今天在web api中遇到了这样一个问题,虽然api的参数类型是string,但只能接收post body中json格式的string,不能接收原始string. web api是这样定义的: pub ...
- 通过微软的cors类库,让ASP.NET Web API 支持 CORS
前言:因为公司项目需要搭建一个Web API 的后端,用来传输一些数据以及文件,之前有听过Web API的相关说明,但是真正实现的时候,感觉还是需要挺多知识的,正好今天有空,整理一下这周关于解决COR ...
- 通过扩展让ASP.NET Web API支持W3C的CORS规范(转载)
转载地址:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html CORS(Cross-Origin Resource Shari ...
- 让ASP.NET Web API支持$format参数的方法
在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可: using System; using Sys ...
- (转)通过扩展让ASP.NET Web API支持JSONP
原文地址:http://www.cnblogs.com/artech/p/3460544.html 同源策略(Same Origin Policy)的存在导致了“源”自A的脚本只能操作“同源”页面的D ...
- [转]让ASP.NET Web API支持$format参数的方法
本文转自:http://www.cnblogs.com/liuzhendong/p/4228592.html 在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数, ...
随机推荐
- #9.5课堂JS总结#循环语句、函数
一.循环语句 1.for循环 下面是 for 循环的语法: for (语句 1; 语句 2; 语句 3) { 被执行的代码块 } 语句 1 在循环(代码块)开始前执行 语句 2 定义运行循环(代码块) ...
- Sass-也许你想和CSS玩耍起来(上篇)
我们努力,我们坚持,共勉! 众所周知,css其实不是一门编程语言,熟悉的人都知道css全称Cascading Style Sheets(层叠样式表)是一种用来表现HTML(标准通用标记语言的一个应用) ...
- VS2012 单元测试之泛型类(Generics Unit Test)
关于单元测试,如果不会用可以参照我的上篇博文————在Visual Studio 2012使用单元测试 首先分享一篇博文,[Visual Studio] 开启Visual Studio 2012通过右 ...
- GCD封装的个人理解和应用
GCD封装的个人理解和应用 特点 >>将GCD封装,使我们从繁琐的方法记忆中解脱出来,能够直接快速的应用. 使用方法 1.将工程中的GCD文件中的9个文件拖入自己的工程中(你自己最好建一个 ...
- “#if 0/#if 1 ... #endif”的作用
1. "#if 0/#if 1 ... #endif"的作用,我们知道,C标准不提供C++里的"//"这样的单行风格注释而只提供"/* */" ...
- IOS 序列化与反序列化NSKeyedUnarchiver
开篇 1到底这个序列化有何作用? 面向对象的程序在运行的时候会创建一个复杂的对象图,经常要以二进制的方法序列化这个对象图,这个过程叫做Archiving. 二进制流可以通过网络或写入文件中. 当你写的 ...
- css sprite简便方法切 《评分五角星》
摘抄自我趣同伴的心得: 大家可以会遇到过要做满意度用星级来评分的情况,类似这种 实现的方法有很多,大家最初想到的可能是根据满意度有多少种情况就切多少种图,然后拼在一张图里面,通过控制图片的位置来实现. ...
- IP 地址分类(A、B、C、D、E类)
互联网上的接口的唯一地址. IP 32位的地址通常表示为四个10进制的数,每个证书对应一个字节,成为点分十进制法(Dotted decimal notation) 如上图首字节整数:A类--0开始,B ...
- postgres扩展开发
扩展开发的基本组成 demo--1.0.sql demo.c demo.control Makefile demo.c当中包含了自定义函数的实现,纯C语言,目录下可包含多个.c文件.demo-1.0. ...
- MongoDB学习笔记~客户端命令行的使用
回到目录 当我们从MongoDB网站下载安装包之后,它会伴随有一系列的工具,服务器程序mongod是我们耳熟能详的了,客户端mongo和性能检测mongostat我们可能就没有用过了,今天主要是介绍一 ...