Plug in Takeoff wings: Add protobuf Support for ASP.

Source: Internet
Author: User
Tags http post pear

There's no time to explain, get in the car.

Get Zaabee.aspnetcoreprotobuf with NuGet

Install-Package Zaabee.AspNetCoreProtobuf

Modify the Configureservices method in the Startup.cs file

public void ConfigureServices(IServiceCollection services){    services.AddMvc(options => { options.AddProtobufSupport(); });}

Make it a mistake ... You can then use the Application/x-protobuf content-type to let ASP. Protobuf for serialization/deserialization.

Test code

Add the following dto in an ASP. NET Core Project

[ProtoContract]public class TestDto{    [ProtoMember(1)] public Guid Id { get; set; }    [ProtoMember(2)] public string Name { get; set; }    [ProtoMember(3)] public DateTime CreateTime { get; set; }    [ProtoMember(4)] public List<TestDto> Kids { get; set; }    [ProtoMember(5)] public long Tag { get; set; }    [ProtoMember(6)] public TestEnum Enum { get; set; }}public enum TestEnum{    Apple,    Banana,    Pear}

Create a new Xunit project and use NuGet to reference Microsoft.AspNetCore.TestHost to build a test class

public class aspnetcoreprotobuftest{private readonly testserver _server;    Private ReadOnly HttpClient _client; Public Aspnetcoreprotobuftest () {_server = new TestServer (new Webhostbuilder (). Usekestrel ().        Usestartup<startup> ()); _client = _server.    CreateClient (); } [Fact] public void Test () {//HTTP Post with Protobuf Response Body _client.        DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/x-protobuf"));        var DTOs = Getdtos ();        var stream = new MemoryStream ();        ProtoBuf.Serializer.Serialize (stream, DTOs);        Httpcontent httpcontent = new Streamcontent (stream); HTTP POST with Protobuf Request Body var responseforpost = _client.        Postasync ("Api/values", httpcontent); var result = protobuf.serializer.deserialize<list<testdto>> (ResponseForPost.Result.Content.ReadAsS Treamasync ().       Result); Assert.true (Comparedtos (Dtos,result)); } private static bool Comparedtos (list<testdto> lstone, list<testdto> lsttwo) {lstone = Lstone? ?        New List<testdto> (); Lsttwo = Lsttwo??        New List<testdto> ();        if (lstone.count! = Lsttwo.count) return false;            for (var i = 0; i < Lstone.count; i++) {var dtoone = lstone[i];            var dtotwo = lsttwo[i];                if (dtoone.id! = Dtotwo.id | | Dtoone.createtime! = Dtotwo.createtime | | Dtoone.enum! = Dtotwo.enum | | Dtoone.name! = Dtotwo.name | | Dtoone.tag! = Dtotwo.tag | | !        Comparedtos (Dtoone.kids, Dtotwo.kids)) return false;    } return true; } private static List<testdto> Getdtos () {return new list<testdto> {new TestD to {Id = Guid.NewGuid (), Tag = long.     MaxValue, Createtime = DateTime.Now, Name = "0",           Enum = testenum.apple, Kids = new List<testdto> {new Te stdto {Id = Guid.NewGuid (), Tag = long.                        MaxValue-1, Createtime = DateTime.Now, Name = "00", Enum = Testenum.banana}, new Testdto {I D = Guid.NewGuid (), Tag = long.                        MaxValue-2, Createtime = DateTime.Now, Name = "01",                Enum = Testenum.pear}}, new Testdto { Id = Guid.NewGuid (), Tag = long.                MaxValue-3, Createtime = DateTime.Now, Name = "1", Enum = Testenum.apple,               Kids = new List<testdto> {new Testdto {Id = Guid.NewGuid (), Tag = long. MaxValue-4, Createtime = DateTime.Now, Name = "Ten", https: I.cnblogs.com/editcategories.aspx?catid=1 Enum = Testenum.banana}, new Test Dto {Id = Guid.NewGuid (), Tag = long.                        MaxValue-5, Createtime = DateTime.Now, Name = "11",    Enum = Testenum.pear}}}; }}
Why do you use PROTOBUF?

Because fast ... In our test of using business data, the serialization/deserialization performance of PROTOBUF is about three times times that of Json.NET, and the serialized volume is about One-second of JSON, which can improve the throughput performance of WEBAPI to a considerable degree.

Disadvantages of Protobuf

The DTO layer must refer to Protobuf-net to add attributes, which in some way leads to code intrusion. Basically dtos belong to Poco, relying on third-party package of words always feel a bit not chaste ... In addition, PROTOBUF serialized data is not visualized, so if you are using Message Queuing or requesting monitoring, consider whether the PROTOBUF is suitable for use in a scenario.

Principle

ASP. NET core is implemented in a middleware-based manner with default Jsonformater (based on json.net), and ASP. NET core selects the corresponding formater based on the content type to handle the serialization of the object. This includes inputformatter (deserialization) and Outputformatter (serialization). So in addition to PROTOBUF, we can add or replace other serialization methods, such as using Jil instead of json.net to improve JSON performance.

The above implementations, as well as the demo and test source code, have been placed on GitHub.

Finally, we wish you a happy new year.

Plug in Takeoff wings: Add protobuf Support for ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.