让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参数, ...
随机推荐
- jquery.datatables中文语言设置
/* * sErrMode * 错误信息显示方式 * 分别为alert和throw,默认为alert */ "sErrMode": "throw", /* * ...
- Android自定义对话框
在android中有自带的对话框,为了美观,很多开发者会使用自定义对话框,如下图: 点击“弹出自定义对话框按钮后”显示如图效果. 首先要自己定义一个xml文件定义自己对话框的样式: <?xml ...
- android TextView多行文本(超过3行)使用ellipsize="end"属性无效问题的解决方法
<TextView android:id="@+id/desc" android:layout_width="match_parent" android: ...
- IOS 绘制圆饼图 简单实现的代码有注释
今天为大家带来IOS 绘图中圆饼的实现 .h文件 #import <UIKit/UIKit.h> @interface ZXCircle : UIView @end .m文件 #impor ...
- ArrayList 浅析示例
package com.smbea.demo; import java.util.ArrayList; import java.util.Iterator; import java.util.List ...
- 用户故事驱动的敏捷开发 – 2. 创建backlog
本系列的第一篇[用户故事驱动的敏捷开发 – 1. 规划篇]跟大家分享了如何使用用户故事来帮助团队创建需求的过程,在这一篇中,我们来看看如何使用这些用户故事和功能点形成产品backlog.产品backl ...
- 5、软件架构师要阅读的书籍 - IT软件人员书籍系列文章
软件架构师在项目中的地位是不言而喻的,其对于项目的需求要相对比较了解,然后对项目代码的结构需要做到覆盖全面.本文就说说作为一个软件架构师需要阅读的一些书籍. 当然,这些书籍都来源于网络,是笔者收集整理 ...
- LeakCanary内存泄漏检测工具使用步骤
LeakCanary内存检测工具使用步骤: 第一步,进入app目录下的build.gradle,在最下面找到dependencies{},里面添加如下三行语句: debugCompile 'com.s ...
- RMAN冷备份异机还原
1:环境准备 在新的服务器上安装ORACLE实例,安装过程中需要注意源服务器与目标服务器的ORACLE_SID一致,另外确保安装路径与源路径一致(不仅是安装目录,甚至包括数据文件.控制文件目录.联机重 ...
- Centos7中所有的关机命令的奇怪现象
今天在研究shutdown,reboot,halt,poweroff几种关机命令的区别是发现他们都是/bin/systemctl的软连接 ls -l /sbin/{shutdown,reboot,ha ...