让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参数, ...
随机推荐
- arcgis server之路网服务发布
路网服务发布首先需要建立好道路的网络集,为了保证道路网络分析的准确性,建立网络集之前,要对道路图层进行拓扑差错,确保道路的连通性.具体操作流程为:道路拓扑差错-建立几何网络集-路网服务发布. 1.道路 ...
- 安装InfoPath 2013后 SharePoint 2010 出现 “找不到 Microsoft.Office.InfoPath, Version=14.0.0....” 的错误的解决方案
1. 症状 您的SharePoint 2010的服务器是不是最近一直出现这个错误呢? Could not load file or assembly 'Microsoft.Office.InfoPat ...
- 用SourceTree合并工程冲突,工程打不开时的操作
1.右键工程 --> 显示包内容 2.打开project.pbxproj文件 3.command + F :搜索“<<<<<” 或“>>>> ...
- nodejs的child_process同步异步
nodejs是一种单线程模型,但是,使用nodejs的child_process模块可以实现多进程任务.利用child_process可以创建子进程,实现子进程和主进程之间的通信. nodejs v0 ...
- 2016年4月21百度iOS实习生在线笔试题&编程题
1.一个人上台阶可以一次上1个,2个,或者3个,问这个人上32层的台阶,总共有几种走法? 思路:先建立数学模型,设3步的走 i 次,2步的走 j 次, 1步的走 k 次,上了3*i + 2*j + 1 ...
- JS实现HTML标签转义及反转义
今天我用ueditor时候遇到一个问题: 我从数据库中读取内容进行编辑的时候,不是有一些html标签嘛,从数据库读出来没有问题: 但是我用asp.net mvc,把读取出来的内容通过ueditor的a ...
- Linq专题之提高编码效率—— 第三篇 你需要知道的枚举类
众所周知,如果一个类可以被枚举,那么这个类必须要实现IEnumerable接口,而恰恰我们所有的linq都是一个继承自IEnumerable接口的匿名类, 那么问题就来了,IEnumerable使了 ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理6
接下来先做角色这一板块的(增删改查),首先要新建一个Role控制器,在添加一个RoleList的视图.表格打算采用的是bootstrap的表格. using System; using System. ...
- YARN基本框架介绍
YARN基本框架介绍 转载请注明出处:http://www.cnblogs.com/BYRans/ 在之前的博客<YARN与MRv1的对比>中介绍了YARN对Hadoop 1.0的完善.本 ...
- linux svn 服务端搭建
环境是centos6.x. 关于团队对代码管理,相信大部分人习惯于svn.不过我个人比较喜欢git的.这个blog git 常用命令 就是介绍git的基本用法.现部署svn服务端方式如下: 1. 用y ...