webapi 中使用 protobuf

相比json来说,好处是速度更快,带宽占用更小。其效果大致等于json+Gzip。

在webapi中使用protobuf的方法为:

 

引用nuget包

Install-Package protobuf-net

 

为DTO添加注解 

    [ProtoContract]
    public class Product
    {

        [ProtoMember(1)]
        public int Id { get; set; }


        [ProtoMember(2)]
        public string Name { get; set; }


        [ProtoMember(3)]
        public long Value { get; set; }

    }

 

 

 注册MediaTypeFormatter

在WebApiConfig文件中添加黄色部分的代码

    public static class WebApiConfig
    {
        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 }
            );
            // config.Formatters.Clear();
            config.Formatters.Add(new ProtoBufFormatter());
         
        }
    }

 

调用接口

http请求报文

GET http://test.cn/webapi/api/product/123 HTTP/1.1
Host: localhost:44605
Connection: keep-alive
Accept: application/x-protobuf

注意黄色的部分

 httpclient请求

            string url = "http://test.cn/webapi/api/product/123";

            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage();
       
            request.RequestUri = new Uri(url);
            request.Method = HttpMethod.Get;
            request.Headers.Add("Accept", "application/x-protobuf");

            HttpResponseMessage result = client.SendAsync(request).Result;

            var stream = result.Content.ReadAsStreamAsync().Result;

            var product= Serializer.Deserialize<Product>(stream);

 

posted @ 2015-12-26 21:24  何德海  阅读(2475)  评论(2编辑  收藏  举报