在Web Api中集成protobuf

时间:2023-03-08 22:15:44
  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三种格式来请求数据

在Web Api中集成protobuf

在Web Api中集成protobuf

在Web Api中集成protobuf

git

https://github.com/xlb378917466/WebApi_protobuf