zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    SERV-U处于“域正离线”怎么办?
    在wampserver3.0.6中配置虚拟主机(设置二级域名)
    解决Win7系统新建选项中无记事本问题
    解决Windows Server 2008 R2安装WAMPSERVER3.0.6问题总结
    php实现定时任务的思路
    https配置for apache
    jquery传值
    有趣的em
    自我感觉良好的配搭
    正则基础整理
  • 原文地址:https://www.cnblogs.com/dehai/p/5043240.html
Copyright © 2011-2022 走看看