asp.net WebApi and protobuff

來源:互聯網
上載者:User

標籤:serialize   相關   prot   host   value   工具   rabl   style   客戶   

protobuff 是Google開發的,在效能上要比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/

 

asp.net WebApi and protobuff

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.