zoukankan      html  css  js  c++  java
  • asp.net WebApi and protobuff

    protobuff 是谷歌开发的,在性能上要比Json xml好很多,对性能要求比较高的时候这个是一个不错的选择,但是这个目前只是一个序列化反序列化的东西,以前原生的只有几种语言的现在在github 上有多种语言有需要的可以自行查看。

    这里将protobuff集成进去,可以自己写一个格式化的也可以安装第三方包。如果是自己写继承MediaTypeFormatter,这里我用的是第三方的包大致说下怎么用。先安装WebApiContrib.Formatting.ProtoBuf 在包管理器里面,然后在WebApiConfig里注册我这里代码是这样的

      config.Formatters.Insert(0, new ProtoBufFormatter());

    这个是更改了序列化方式,也可以设置指定的类型这时候代码如下

    ProtoBufFormatter.Model.Add(typeof (Item), true);
    ProtoBufFormatter.Model.CompileInPlace();

    然后新增一个实体Contact这里代码如下:

        [ProtoContract]
        public class Contact
    
        {
    
            [ProtoMember(1)]
            public int Id { get; set; }
    
            [ProtoMember(2)]
            public string FirstName { get; set; }
    
            [ProtoMember(3)]
            public string LastName { get; set; }
    
            [ProtoMember(4)]
            public string Address { get; set; }
    
        }

    新建一个Controller 这里是restfull风格的

     

     public class TestController : ApiController
        {
            public IEnumerable<Contact> Get()
            {
                var list = new List<Contact>
                {
                    new Contact() { Id=123456789,FirstName="t",LastName="l",Address="front.ltd"},
                   
                };
                list.Add(new Contact() { Id = 987654321, FirstName = "x", LastName = "a", Address = "front.ltd" });
                list.Add(new Contact() { Id = 330987260, FirstName = "d", LastName = "x", Address = "front.ltd" });
                return list;
            }
           
           
            
    
            // POST api/<controller>
            public void Post([FromBody]Contact value)
            {
                Console.WriteLine("---");
                Console.WriteLine(value.ToString());
                Debug.WriteLine("has receive the data");
                Debug.WriteLine(value);
            }
    
            // PUT api/<controller>/5
            public void Put(int id, [FromBody]string value)
            {
            }
    
            // DELETE api/<controller>/5
            public void Delete(int id)
            {
            }

      这个时候可以通过客户端访问了 这时候的客户端是这个样子的

      Debug.WriteLine("start");
                var serviceUri = new Uri("http://localhost:12706/api/");
                var client = new HttpClient { BaseAddress = new Uri("http://localhost:12706/api/Test/") };
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
                var response = client.GetAsync("Test/").Result;
              
                var r = response.Content.ReadAsStreamAsync();
                if (r.IsCompleted)
                {
                    var con=DeSerialize<List<Contact>>(r.Result);
                  
               
                    con.ForEach(model =>
                    {
    
                        Console.WriteLine($"the first name is {model.FirstName } the address:{model.Address}");
                    });
               
                 

    我这里是在控制台里运行的,也可以在js以及其他程序里去访问,网上这种文章不少就不在这里说了。刚才是获取如果是要post 代码是这样的

     var contractModel = new Contact();
                contractModel.FirstName = "xiao";
                contractModel.Address = "front.ltd";
                var contentRequest = new StringContent(Serialize<Contact>(contractModel));
                contentRequest.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf");
                Debug.WriteLine(contentRequest);
                var res =   client.PostAsync("Test/", contentRequest);
                if (res.IsCompleted)
                {
                    Console.WriteLine(res.Result);
                }

    这个就是整个过程了,如果有谁需要这个demo 可以留言。在整合的时候遇到了一些问题,这个ProtoContract 标记的跟用protobuff-net的工具产生的代码不太一样,不能混用。最好新建的实体类是一式两份客户端与服务端都要使用。这里参考了其他的两个链接,因为情况不太一样导致调试还花了不少时间

    相关链接:

    http://www.cnblogs.com/shanyou/archive/2012/01/22/using-google-protocol-buffers-hypermedia-type-with-wcf-restful-services-a-media-type.html

    http://www.strathweb.com/2013/02/asp-net-web-api-and-protocol-buffers/

  • 相关阅读:
    太精辟了!从学校到职场的十条经典语录!
    平庸领导下跳棋,伟大领导下象棋(转)
    新官上任前的十一大基本功
    病母私自出房有感
    你为何还会出现在我梦里
    创业辛酸
    Goldengate can't extract data from compressed table
    配置GoldenGate同步DDL语句(3)
    Goldengate各build与Oracle数据库版本间的兼容性
    11g新特性:Note raised when explain plan for create index
  • 原文地址:https://www.cnblogs.com/EncryptingLife/p/6139664.html
Copyright © 2011-2022 走看看