-
安装WebApiContrib.Formatting.ProtoBuf
- Install-Package WebApiContrib.Formatting.ProtoBuf
-
注册ProtoBufFormatter
-
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 } ); } }
-
-
设置DTO
- 注意这里的Order是必须的
-
[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; } }
-
客户端调用
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三种格式来请求数据
https://github.com/xlb378917466/WebApi_protobuf