在Web Api中集成protobuf

  1. 安装WebApiContrib.Formatting.ProtoBuf

    1. Install-Package WebApiContrib.Formatting.ProtoBuf
  2. 注册ProtoBufFormatter

    1. public static class WebApiConfig
          {
              public static void Register(HttpConfiguration config)
              {
                  config.Formatters.Add(new ProtoBufFormatter());
                  // Web API configuration and services
      
                  // Web API routes
                  config.MapHttpAttributeRoutes();
      
                  config.Routes.MapHttpRoute(
                      name: "DefaultApi",
                      routeTemplate: "api/{controller}/{id}",
                      defaults: new { id = RouteParameter.Optional }
                  );
              }
          }
      
  3. 设置DTO

    1. 注意这里的Order是必须的
    2.  [DataContract]
          public class Item
          {
              [DataMember(Order = 1)]
              public int Id { get; set; }
              [DataMember(Order = 2)]
              public string Name { get; set; }
              [DataMember(Order = 3)]
              public long Value { get; set; }
          }
      

       

  4. 客户端调用

      static  void Main(string[] args)
        {
      
            var httpClient = new HttpClient();
         
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-protobuf"));

            var response = httpClient.GetAsync("http://localhost:60339/api/Default/GetItem").Result;
            //把 ProtoBuf Stream 反序列化成 集合
            var  obj = (RuntimeTypeModel.Default).Deserialize(response.Content.ReadAsStreamAsync().Result, null, typeof(List<Item>)) as List<Item>;
            
            Console.WriteLine(obj.Count);

            //设置请求头
            var content = new ObjectContent<List<Item>>(obj, new ProtoBufFormatter());
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf");

            var postResponse1=  httpClient.PostAsync("http://localhost:60339/api/Default/PostItem", content).Result;
            var postResult = postResponse1.Content.ReadAsStreamAsync().Result;
            var intValue = (RuntimeTypeModel.Default).Deserialize(postResult, null, typeof(int));

            Console.WriteLine(intValue);
            Console.ReadKey();
        }

 使用Fiddler发送Accept 分别为Json,Xml,Protobuf三种格式来请求数据

 

 

git

 https://github.com/xlb378917466/WebApi_protobuf

 

转载于:https://www.cnblogs.com/LittleFeiHu/p/6249231.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值